# Amazon Athena (/docs/analytics/athena) ## What it is [#what-it-is]
![Amazon Athena: logs such as VPC Flow Logs, ELB logs and CloudTrail land in S3 as CSV, JSON or Parquet; Athena queries them in place with serverless SQL, writes results to an S3 results bucket, and feeds QuickSight reports and dashboards; you pay 5 dollars per TB scanned](/diagrams/analytics-athena.light.svg) ![Amazon Athena: logs such as VPC Flow Logs, ELB logs and CloudTrail land in S3 as CSV, JSON or Parquet; Athena queries them in place with serverless SQL, writes results to an S3 results bucket, and feeds QuickSight reports and dashboards; you pay 5 dollars per TB scanned](/diagrams/analytics-athena.dark.svg)
Point Athena at S3 and write SQL.
**[Amazon Athena](/docs/glossary#term-amazon-athena)** is a **serverless** query service that analyses data **stored in Amazon S3** with **standard SQL**. - There's nothing to load or provision: you define a table over files in S3, then query them. - Supports **CSV, JSON, ORC, Avro, Parquet** (and more, such as logs and Amazon Ion). - Query **results are written to S3**. - **Pricing:** **$5 per TB of data scanned** (10 MB minimum per query). DDL statements and failed queries are free. - Commonly used with **QuickSight** for reports and dashboards, and with the **Glue Data Catalog** for table definitions. - Athena can also run **Apache Spark** code in notebooks. **Use cases:** business intelligence, ad-hoc analysis and reporting; querying **VPC Flow Logs, ELB logs, CloudTrail trails**, [S3 access logs](/docs/s3/mfa-delete-access-logs#s3-server-access-logs) and other AWS logs. The slides say Athena is built on **Presto**. Today's engine (engine version 3) is built on **Trino**, the successor project to Presto, with improvements from both. For the exam this changes nothing: Athena is serverless SQL on S3. ## Performance and cost [#performance-and-cost] You pay for the data **scanned**, so scanning less is both **faster and cheaper**: - **Use columnar data** (**Apache Parquet** or **ORC**). A query reads only the columns it needs: a huge performance gain and a big saving. Use **[Glue](/docs/analytics/glue#convert-data-to-parquet)** to convert your data to Parquet or ORC. - **Compress the data** for smaller reads (Snappy, gzip, zstd, LZ4, bzip2…). - **Partition datasets** in S3, so queries filter on **virtual columns** and skip whole folders: - `s3://bucket/table/=/=/…` - for example `s3://athena-examples/flight/parquet/year=1991/month=1/day=1/` - **Use larger files** (over about 128 MB) to cut overhead. Many small files slow queries down. For example, a 3 TB CSV file costs $15 per full scan. Compressed 3:1 with gzip, it costs $5. Stored as Parquet, a query that reads one of four columns scans only about 0.25 TB: **$1.25**. ## Federated query [#federated-query]
![Athena Federated Query: one SQL query in Athena runs through data source connectors on Lambda to reach DynamoDB, RDS and Aurora, Redshift, DocumentDB, ElastiCache or an on-premises database over JDBC; results are stored in S3](/diagrams/analytics-athena-federated.light.svg) ![Athena Federated Query: one SQL query in Athena runs through data source connectors on Lambda to reach DynamoDB, RDS and Aurora, Redshift, DocumentDB, ElastiCache or an on-premises database over JDBC; results are stored in S3](/diagrams/analytics-athena-federated.dark.svg)
One query across many data stores.
**[Athena Federated Query](/docs/glossary#term-athena-federated-query)** runs SQL across data stored in **relational, non-relational, object and custom data sources**, in AWS or on premises. - It uses **data source connectors**, which run on **AWS Lambda**, to read each source (CloudWatch Logs, DynamoDB, RDS, Redshift, DocumentDB, ElastiCache, HBase on EMR, on-premises databases over JDBC…). - You can **join** data from several sources in one query. - Store the **results back in S3**. Since April 2026, some newly created connectors are registered in the Glue Data Catalog and no longer need a Lambda function in your account. The exam idea stays the same: **connectors** let Athena query data outside S3. ## Real-world examples [#real-world-examples] - **A security team** queries six months of VPC Flow Logs in S3 to find every connection to a suspicious IP address, paying only for the data scanned. - **A retailer** converts daily CSV sales files to Parquet, partitioned by date, and its dashboards query only the last week: cost drops by more than 90%. - **An analyst** joins customer orders in DynamoDB with product data in Aurora in one Athena query, with federated query. ## Exam tips [#exam-tips] - **"Analyse data in S3 using serverless SQL"** → Athena. - **"Query VPC Flow Logs, ELB logs, CloudTrail logs ad hoc"** → Athena. - **"Reduce Athena cost or improve performance"** → columnar formats (Parquet, ORC), compression, partitioning, larger files. - **"Run SQL across DynamoDB, RDS and on-premises data without moving it"** → Athena Federated Query. - **"Dashboards on Athena results"** → QuickSight. ## Common traps [#common-traps] - **"Athena needs a cluster" or "load the data into Athena first."** It's serverless and queries files in place. - **"Pay per hour."** Athena charges per TB scanned (unless you buy capacity reservations). - **"Partitioning by every column."** Too many small partitions and files make queries slower. ## Hands-on lab: query a CSV file with Athena [#hands-on-lab-query-a-csv-file-with-athena] **Goal:** create a table over a CSV file in S3 and query it. Athena charges $5 per TB scanned with a 10 MB minimum per query, so ten test queries cost about **$0.0005**. S3 storage for a tiny file is a fraction of a cent. Any Region works. ### Upload the data [#upload-the-data] Create a bucket `saa-athena-` with folders `data/` and `results/`. Upload a file `data/sales.csv`: ```text region,product,amount eu,shoes,120 us,shoes,80 eu,hats,45 ``` ### Point Athena at the results folder [#point-athena-at-the-results-folder] Open **Athena → Query editor → Settings → Manage** and set the query result location to `s3://saa-athena-/results/`. ### Create the table [#create-the-table] Run: ```sql CREATE EXTERNAL TABLE sales (region string, product string, amount int) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LOCATION 's3://saa-athena-/data/' TBLPROPERTIES ('skip.header.line.count'='1'); ``` ### Query it [#query-it] Run `SELECT region, SUM(amount) FROM sales GROUP BY region;`. Look at **Data scanned** under the results. **Expected result:** `eu 165` and `us 80`, with a few bytes scanned (billed as 10 MB). **Clean up:** run `DROP TABLE sales;`, then empty and delete the bucket. ## AWS documentation [#aws-documentation] - [What is Amazon Athena?](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) - [Amazon Athena pricing](https://aws.amazon.com/athena/pricing/) - [Optimize data for Athena](https://docs.aws.amazon.com/athena/latest/ug/performance-tuning-data-optimization-techniques.html) - [Use Amazon Athena Federated Query](https://docs.aws.amazon.com/athena/latest/ug/federated-queries.html) # Big data ingestion pipeline (/docs/analytics/big-data-pipeline) ## The requirements [#the-requirements] A company wants a pipeline that: - is **fully serverless**; - **collects data in real time**; - **transforms** the data; - lets them **query** the transformed data **using SQL**; - stores the **reports** created by the queries **in S3**; - **loads** that data into a **warehouse** and creates **dashboards**. ## The architecture [#the-architecture]
![A serverless big data ingestion pipeline: IoT Core sends device data to Kinesis Data Streams in real time; Firehose, with a Lambda transform, delivers it to an S3 ingestion bucket about every minute; the S3 event goes through an optional SQS queue to a Lambda function that runs an Athena query over the ingestion data; results land in a reporting bucket used by QuickSight dashboards and Redshift Serverless](/diagrams/analytics-big-data-pipeline.light.svg) ![A serverless big data ingestion pipeline: IoT Core sends device data to Kinesis Data Streams in real time; Firehose, with a Lambda transform, delivers it to an S3 ingestion bucket about every minute; the S3 event goes through an optional SQS queue to a Lambda function that runs an Athena query over the ingestion data; results land in a reporting bucket used by QuickSight dashboards and Redshift Serverless](/diagrams/analytics-big-data-pipeline.dark.svg)
From devices to dashboards with no servers.
1. **IoT Core** harvests data from IoT devices. 2. **Kinesis Data Streams** collects it in **real time**. 3. **Data Firehose** delivers it to S3 in **near real time** (about every minute), with **Lambda** helping Firehose **transform** the data. 4. The **ingestion bucket** stores the raw data. 5. **S3** can send event notifications to **SQS** (optional; S3 could also invoke Lambda directly). 6. **Lambda** subscribes to SQS and **runs an Athena query**. 7. **Athena** is serverless SQL; it pulls data from the ingestion bucket and **stores the results in S3**. 8. The **reporting bucket** contains the analysed data, used by reporting tools such as **QuickSight** and by **Redshift** (here Redshift Serverless, to stay serverless). ## Why each piece [#why-each-piece] - **Kinesis Data Streams** rather than SQS: ordered, replayable, real-time streams with several consumers. - **Firehose** rather than custom code: managed delivery and batching into S3, with optional Lambda transformation. - **SQS between S3 and Lambda:** a buffer that absorbs bursts and retries failed work. - **Athena** rather than a cluster: SQL on S3 with nothing to run between queries. - **Redshift Serverless** rather than a provisioned cluster: no capacity to manage, pay when queried. ## Exam tips [#exam-tips] - **"Serverless pipeline: collect in real time, transform, query with SQL, dashboards"** → Kinesis Data Streams → Firehose (+ Lambda) → S3 → Athena → QuickSight. - **"Near real-time delivery to S3"** → Firehose. **"Real-time ingestion"** → Kinesis Data Streams. - **"Transform records in flight with Firehose"** → a Lambda transformation. ## Common traps [#common-traps] - **"Firehose is real time."** It buffers: near real time. - **"Use EMR for a fully serverless pipeline."** Classic EMR runs clusters; Athena, Glue or EMR Serverless fit "serverless". ## Check yourself [#check-yourself] Building the whole pipeline needs Kinesis shards and several services running, so instead: IoT Core → Kinesis Data Streams → Firehose (Lambda transform) → S3; a scheduled or event-driven Lambda runs Athena queries that write reports to S3; QuickSight builds the dashboard on Athena or the reports. ## AWS documentation [#aws-documentation] - [What is Amazon Data Firehose?](https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html) - [Transform source data in Amazon Data Firehose](https://docs.aws.amazon.com/firehose/latest/dev/data-transformation.html) - [What is Amazon Athena?](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) # Data Exchange, Data Pipeline and Kinesis Video Streams (/docs/analytics/data-exchange-data-pipeline) These three services are on the exam guide's in-scope list but not in the course slides. This page is written from the AWS documentation. ## AWS Data Exchange [#aws-data-exchange] **[AWS Data Exchange](/docs/glossary#term-aws-data-exchange)** lets you **find, subscribe to and use third-party data** in the cloud: market data, weather, demographics, healthcare, financial data and more. - **Providers** publish **data products** in the **AWS Marketplace** catalogue; **subscribers** pay for and receive them. - Data set types: **files** (delivered to S3), **APIs**, **Amazon Redshift** tables (data sharing), **Amazon S3** data in place, and **Lake Formation** tables (preview). - Subscribed data updates arrive automatically, so you don't build ingestion from each vendor. - Free **Open Data on AWS** datasets are also available. **Use case:** a hedge fund subscribes to a stock-price dataset and queries it in its own Redshift cluster as soon as the provider updates it. ## AWS Data Pipeline [#aws-data-pipeline] **[AWS Data Pipeline](/docs/glossary#term-aws-data-pipeline)** **schedules and runs data movement and processing** between AWS services and on-premises data: for example, copy web server logs to S3 every day, then launch a weekly EMR cluster to build traffic reports. - It runs the work on **EC2 instances** or **EMR clusters** that it creates, and handles dependencies, retries and failure notifications. AWS Data Pipeline is **no longer available to new customers** and is in **maintenance mode** (no new features or Regions). AWS recommends **AWS Glue**, **Step Functions** or **Amazon MWAA** (managed Apache Airflow) instead. If a question offers Data Pipeline alongside one of these, the modern service is usually the better answer. ## Amazon Kinesis Video Streams [#amazon-kinesis-video-streams] **[Amazon Kinesis Video Streams](/docs/glossary#term-amazon-kinesis-video-streams)** **streams live video from devices to AWS** for analytics, machine learning and playback. - **Producers:** security cameras, body cameras, phones, dashcams; they can also send audio, images and radar data. One producer can send one or more streams. - Video is **stored durably**, **encrypted**, and **time-indexed** for the **retention period** you choose. - **Consumers** process it in real time or in batches: for example **[Amazon Rekognition](/docs/ml/vision-documents#amazon-rekognition) Video** for face or object detection, or your own ML models. - Supports **playback** (HLS) and **two-way, real-time media with WebRTC**. **Use case:** a smart-home company streams doorbell camera video to Kinesis Video Streams, detects people with Rekognition, and lets owners watch live from their phone. ## Exam tips [#exam-tips] - **"Subscribe to third-party datasets", "buy data from providers"** → AWS Data Exchange. - **"Schedule data movement and processing"** → today Glue, Step Functions or MWAA; Data Pipeline only for existing customers. - **"Stream video from cameras for ML analysis or playback"** → Kinesis Video Streams. ## Common traps [#common-traps] - **"Kinesis Data Streams for video from cameras."** Video goes to Kinesis Video Streams. - **"Build a new workflow on Data Pipeline."** It's closed to new customers. ## AWS documentation [#aws-documentation] - [What is AWS Data Exchange?](https://docs.aws.amazon.com/data-exchange/latest/userguide/what-is.html) - [What is AWS Data Pipeline?](https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/what-is-datapipeline.html) - [What is Amazon Kinesis Video Streams?](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/what-is-kinesis-video.html) # Amazon EMR (/docs/analytics/emr) ## What it is [#what-it-is] **[Amazon EMR](/docs/glossary#term-amazon-emr)** (formerly *Elastic MapReduce*) helps you create **Hadoop clusters** (big data) to **analyse and process vast amounts of data**. - Clusters can be made of **hundreds of EC2 instances**. - EMR comes bundled with **Apache Spark, Hive, HBase, Presto/Trino, Flink** and other open-source tools. - EMR takes care of **provisioning and configuration**. - **Auto scaling**, and integration with **Spot Instances** for lower cost. - Reads and writes data in **S3** (EMRFS) as well as the cluster's own HDFS. **Use cases:** data processing, machine learning, web indexing, big data (when you need the open-source frameworks or control over the cluster). Besides clusters on EC2, there's **EMR Serverless** (run Spark and Hive jobs with no cluster to manage) and **EMR on EKS** (run Spark on your Kubernetes cluster). ## Node types and purchasing [#node-types-and-purchasing]
![Amazon EMR node types: the primary node manages the cluster; core nodes run tasks and store HDFS data; optional task nodes only run tasks and are often Spot Instances; nodes can be On-Demand, Reserved or Spot, and clusters can be long-running or transient](/diagrams/analytics-emr-nodes.light.svg) ![Amazon EMR node types: the primary node manages the cluster; core nodes run tasks and store HDFS data; optional task nodes only run tasks and are often Spot Instances; nodes can be On-Demand, Reserved or Spot, and clusters can be long-running or transient](/diagrams/analytics-emr-nodes.dark.svg)
Core nodes hold data; task nodes only compute.
- **Primary node** (called the *master node* in the slides): **manages the cluster**, coordinates work and tracks health. Long-running. You can run **three primary nodes** for high availability. - **Core nodes:** **run tasks and store data** (HDFS). Long-running. Removing them risks losing data. - **Task nodes** (optional): **just run tasks**, with no data stored. Usually **Spot**, because losing one only loses work in progress. **Purchasing options:** - **On-Demand:** reliable, predictable, won't be terminated. Good for the primary and core nodes. - **Reserved** (1 or 3 years): cost savings; EMR **uses them automatically** when available. - **Spot Instances:** much cheaper, can be terminated, less reliable. Good for task nodes. **Cluster types:** - **Long-running** cluster: stays up and accepts work (the default). Use Reserved Instances for its steady part. - **Transient** (temporary) cluster: starts, runs its steps, then **terminates** automatically. You pay only while the job runs. ## Real-world examples [#real-world-examples] - **A media company** runs a transient EMR cluster every night: Spark jobs process the day's clickstream from S3, write results back to S3, and the cluster shuts down. - **A research team** adds Spot task nodes to a long-running cluster to finish a large job faster and cheaper, keeping core nodes on On-Demand so no HDFS data is lost. ## Exam tips [#exam-tips] - **"Hadoop", "Spark", "Hive", "HBase", "big data cluster"** → EMR. - **"Cheapest compute for EMR that can be interrupted"** → Spot task nodes. - **"Don't lose data if nodes are reclaimed"** → keep core nodes On-Demand (or Reserved); use Spot for task nodes. - **"Run a nightly batch job and pay only while it runs"** → transient cluster (or EMR Serverless). - **"Spark without managing clusters"** → EMR Serverless (or Glue for ETL). ## Common traps [#common-traps] - **"Run core nodes on Spot to save money."** Core nodes store HDFS data; losing them can lose data. Use Spot for task nodes. - **"EMR is serverless."** Classic EMR runs clusters of EC2 instances; only EMR Serverless removes them. ## Check yourself [#check-yourself] An EMR cluster runs at least three EC2 instances plus an EMR charge per instance, so instead: Run a transient EMR cluster that terminates after its steps, with On-Demand primary and core nodes and extra Spot task nodes (or EMR Serverless). ## AWS documentation [#aws-documentation] - [What is Amazon EMR?](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html) - [Primary, core and task nodes](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-master-core-task-nodes.html) - [Long-running and transient clusters](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-longrunning-transient.html) - [What is Amazon EMR Serverless?](https://docs.aws.amazon.com/emr/latest/EMR-Serverless-UserGuide/emr-serverless.html) # Managed Flink and Amazon MSK (/docs/analytics/flink-msk) ## Amazon Managed Service for Apache Flink [#amazon-managed-service-for-apache-flink]
![Amazon Managed Service for Apache Flink: applications written in Java, Python or SQL read from Kinesis Data Streams or Amazon MSK and write results to destinations such as S3, another Kinesis data stream or OpenSearch; Firehose cannot be a source](/diagrams/analytics-flink.light.svg) ![Amazon Managed Service for Apache Flink: applications written in Java, Python or SQL read from Kinesis Data Streams or Amazon MSK and write results to destinations such as S3, another Kinesis data stream or OpenSearch; Firehose cannot be a source](/diagrams/analytics-flink.dark.svg)
Process streams from Kinesis or Kafka in real time.
**[Amazon Managed Service for Apache Flink](/docs/glossary#term-amazon-managed-service-for-apache-flink)** was previously named *Kinesis Data Analytics for Apache Flink*. - **Apache Flink** (Java, Scala, Python or SQL) is a framework for **processing data streams**: filtering, aggregating over time windows, joining streams, detecting anomalies. - **Sources:** **Kinesis Data Streams** and **Amazon MSK**. - Run any Apache Flink application on a **managed cluster** on AWS: - provisioned compute resources, parallel computation, **automatic scaling**; - **application backups** (implemented as checkpoints and snapshots); - use any Apache Flink programming feature to transform data. - **Important:** Flink **does not read from Amazon Data Firehose**. ## Amazon MSK [#amazon-msk] **[Amazon MSK](/docs/glossary#term-amazon-msk)** (Managed Streaming for Apache Kafka) is **fully managed Apache Kafka** on AWS: an **alternative to Amazon Kinesis**. - Lets you **create, update and delete clusters**. - MSK creates and manages the **Kafka broker nodes** (and the ZooKeeper nodes or KRaft controllers that keep cluster metadata) for you. - Deploy the MSK cluster **in your VPC, across multiple AZs** (up to 3, for high availability). - **Automatic recovery** from common Apache Kafka failures. - Data is stored on **EBS volumes for as long as you want** (and tiered storage can move older data to a cheaper tier). - **MSK Serverless:** run Apache Kafka **without managing capacity**. MSK provisions resources and scales compute and storage automatically. It requires IAM access control. - **MSK Connect** runs managed Kafka Connect connectors to move data to and from S3, OpenSearch and databases. ### Apache Kafka at a high level [#apache-kafka-at-a-high-level]
![Amazon MSK: producers you write send records to topics on an MSK cluster whose brokers replicate partitions across up to three Availability Zones; consumers such as Managed Service for Apache Flink, Glue streaming ETL, Lambda or your own apps on EC2, ECS or EKS read them](/diagrams/analytics-msk.light.svg) ![Amazon MSK: producers you write send records to topics on an MSK cluster whose brokers replicate partitions across up to three Availability Zones; consumers such as Managed Service for Apache Flink, Glue streaming ETL, Lambda or your own apps on EC2, ECS or EKS read them](/diagrams/analytics-msk.dark.svg)
Producers write to topics; consumers poll them.
1. **Producers** (your code) take data from sources such as Kinesis, IoT or RDS and **write it to a topic**. 2. The topic's partitions live on **brokers**, and are **replicated** to other brokers in other AZs. 3. **Consumers** (your code) **poll from the topic** and send the data on, to EMR, S3, SageMaker, Kinesis, RDS… **MSK consumers** include: - **Managed Service for Apache Flink**; - **AWS Glue** streaming ETL jobs (powered by Apache Spark Streaming); - **Lambda** (MSK as an event source); - your own applications on **EC2, ECS or EKS**. ## Kinesis Data Streams vs Amazon MSK [#kinesis-data-streams-vs-amazon-msk] **Kinesis Data Streams:** - Records up to **10 MiB** (1 MB in the slides). - Data streams with **shards**. - **Shard splitting and merging.** - TLS in-flight encryption. - KMS at-rest encryption. **Amazon MSK:** - **1 MB** messages by default, configurable higher (for example 10 MB). - Kafka **topics with partitions**. - You can **only add partitions** to a topic. - **PLAINTEXT or TLS** in-flight encryption. - KMS at-rest encryption. Choose MSK when you already use **Kafka** (tools, code, skills) or need Kafka features; choose Kinesis for a simpler, AWS-native, serverless stream. Kinesis Data Streams now accepts records of up to **10 MiB**, not 1 MB, so record size alone is no longer a reason to pick MSK. MSK has also added **Express brokers** (more throughput per broker, faster scaling, no storage to manage) and **KRaft** mode, which replaces ZooKeeper. ## Real-world examples [#real-world-examples] - **A ride-hailing app** streams driver locations into Kinesis Data Streams, and a Managed Flink application computes surge pricing per area every 10 seconds. - **A bank** moves its on-premises Kafka cluster to MSK with no code changes, and a Glue streaming ETL job writes the transactions to S3. ## Exam tips [#exam-tips] - **"Real-time analytics or transformations on a stream"** → Managed Service for Apache Flink. - **"Kafka", "migrate an existing Kafka cluster", "Kafka without managing servers"** → Amazon MSK (MSK Serverless). - **"Read from MSK"** → Flink, Glue streaming ETL, Lambda, or apps on EC2/ECS/EKS. - **"Kinesis Data Analytics"** in an old question → Managed Service for Apache Flink. ## Common traps [#common-traps] - **"Flink reads from Firehose."** Its streaming sources are Kinesis Data Streams and MSK. - **"MSK is serverless by default."** Provisioned MSK has brokers you size; only MSK Serverless removes capacity management. - **"Remove partitions from a Kafka topic."** You can only add them. ## Check yourself [#check-yourself] An MSK cluster or Flink application costs dollars per day even when idle, so instead: Move to Amazon MSK; MSK Serverless removes capacity management completely (clients must use IAM access control). The Kafka APIs stay the same. A Managed Service for Apache Flink application reading from the stream, with one-minute windows, writing the results to a destination such as S3 or another stream. ## AWS documentation [#aws-documentation] - [What is Amazon Managed Service for Apache Flink?](https://docs.aws.amazon.com/managed-flink/latest/java/what-is.html) - [What is Amazon MSK?](https://docs.aws.amazon.com/msk/latest/developerguide/what-is-msk.html) - [What is MSK Serverless?](https://docs.aws.amazon.com/msk/latest/developerguide/serverless.html) - [Amazon MSK Express brokers](https://docs.aws.amazon.com/msk/latest/developerguide/msk-broker-types-express.html) - [Metadata management (ZooKeeper and KRaft)](https://docs.aws.amazon.com/msk/latest/developerguide/metadata-management.html) # AWS Glue (/docs/analytics/glue) ## What it is [#what-it-is] **[AWS Glue](/docs/glossary#term-aws-glue)** is a managed **[extract, transform and load (ETL)](/docs/glossary#term-etl)** service. - Useful to **prepare and transform data for analytics**. - **Fully serverless:** no cluster to manage; jobs run on a managed Apache Spark engine (or Python shell). - Connects to more than 70 data sources: for example, extract from **S3** and **RDS**, transform, and load into a **Redshift** data warehouse. ## Convert data to Parquet [#convert-data-to-parquet]
![Converting data to Parquet with Glue: a CSV file uploaded to the input bucket sends an S3 event to a Lambda function or EventBridge, which starts a Glue ETL job that reads the CSV and writes Parquet to the output bucket, where Athena queries it more cheaply](/diagrams/analytics-glue-parquet.light.svg) ![Converting data to Parquet with Glue: a CSV file uploaded to the input bucket sends an S3 event to a Lambda function or EventBridge, which starts a Glue ETL job that reads the CSV and writes Parquet to the output bucket, where Athena queries it more cheaply](/diagrams/analytics-glue-parquet.dark.svg)
CSV in, Parquet out, cheaper Athena queries.
A classic pattern: 1. Files are uploaded (S3 PUT) as **CSV** to an input bucket. 2. An **[S3 event notification](/docs/s3/event-notifications)** triggers a **Lambda** function (EventBridge works too), which **starts a Glue ETL job**. 3. The job **converts the data to Parquet** and writes it to an output bucket. 4. **Athena** queries the Parquet files: much less data scanned, so faster and cheaper. ## Glue Data Catalog [#glue-data-catalog]
![Glue Data Catalog: a Glue crawler reads data in S3, RDS, DynamoDB and JDBC databases, infers the schema and writes table metadata to the Data Catalog, which Athena, Redshift Spectrum, Amazon EMR and Glue ETL jobs use to find and read the data](/diagrams/analytics-glue-catalog.light.svg) ![Glue Data Catalog: a Glue crawler reads data in S3, RDS, DynamoDB and JDBC databases, infers the schema and writes table metadata to the Data Catalog, which Athena, Redshift Spectrum, Amazon EMR and Glue ETL jobs use to find and read the data](/diagrams/analytics-glue-catalog.dark.svg)
One catalogue of datasets for every analytics service.
The **[Glue Data Catalog](/docs/glossary#term-glue-data-catalog)** is a **catalogue of datasets**: databases and tables that hold **metadata** (schema, format, location), not the data itself. - A **Glue crawler** connects to **S3, RDS, DynamoDB** or any **JDBC** database, **infers the schema** and **writes the metadata** into the catalog. - **Glue jobs** use it for ETL. - **Athena**, **Redshift Spectrum** and **EMR** use it for **data discovery**: they read table definitions from the catalog to query the data. ## Things to know at a high level [#things-to-know-at-a-high-level] - **Glue job bookmarks:** remember what a job already processed, to **prevent re-processing old data** on the next run. - **Glue DataBrew:** **clean and normalize** data with more than 250 **pre-built transformations**, visually, with no code. - **Glue Studio:** a **visual interface** to create, run and monitor ETL jobs. - **Glue Streaming ETL** (built on Apache Spark Structured Streaming): process streams from **Kinesis Data Streams, Apache Kafka and MSK** continuously. ## Real-world examples [#real-world-examples] - **A logistics company** crawls its S3 bucket of shipment files every night; new partitions appear in the Data Catalog, and analysts query them in Athena the next morning. - **A bank** uses a Glue job with bookmarks to load only the new transaction files from S3 into Redshift each hour. ## Exam tips [#exam-tips] - **"Serverless ETL", "transform data for analytics"** → Glue. - **"Convert CSV to Parquet (or ORC) to reduce Athena cost"** → Glue ETL job. - **"Discover data and build a schema automatically"** → Glue crawler + Data Catalog. - **"Central metadata store for Athena, Redshift Spectrum and EMR"** → Glue Data Catalog. - **"Don't reprocess data already handled"** → job bookmarks. - **"Clean data visually without code"** → Glue DataBrew. ## Common traps [#common-traps] - **"The Data Catalog stores the data."** It stores only metadata; the data stays in S3 or the database. - **"Glue needs a cluster."** It's serverless. ## Check yourself [#check-yourself] Glue jobs bill per DPU-hour (about $0.44, with a 1-minute minimum), so instead: Run a Glue ETL job (started by an S3 event or a schedule, with job bookmarks) that converts the new files to compressed, partitioned Parquet, and point the Athena table at the Parquet data. ## AWS documentation [#aws-documentation] - [What is AWS Glue?](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) - [Getting started with the Glue Data Catalog](https://docs.aws.amazon.com/glue/latest/dg/start-data-catalog.html) - [Tracking processed data using job bookmarks](https://docs.aws.amazon.com/glue/latest/dg/monitor-continuations.html) - [What is AWS Glue DataBrew?](https://docs.aws.amazon.com/databrew/latest/dg/what-is.html) # Analytics (/docs/analytics) ## What analytics means on AWS [#what-analytics-means-on-aws] **Analytics** is turning large amounts of raw data (logs, clicks, sales, sensor readings) into answers: reports, dashboards, search results, alerts. On AWS this is a chain of managed services, most of them serverless.
![Analytics services by stage: ingest with Kinesis Data Streams, Firehose and Amazon MSK; store in S3, Redshift and OpenSearch; prepare with AWS Glue and Lake Formation; analyze with Athena, EMR and Managed Service for Apache Flink; visualize with QuickSight](/diagrams/analytics-services-map.light.svg) ![Analytics services by stage: ingest with Kinesis Data Streams, Firehose and Amazon MSK; store in S3, Redshift and OpenSearch; prepare with AWS Glue and Lake Formation; analyze with Athena, EMR and Managed Service for Apache Flink; visualize with QuickSight](/diagrams/analytics-services-map.dark.svg)
The analytics services, stage by stage.
1. **Ingest:** streams arrive through [Kinesis Data Streams and Firehose](/docs/integration/kinesis) or **Amazon MSK** (managed Kafka). 2. **Store:** cheap, durable files in **S3** (the **[data lake](/docs/glossary#term-data-lake)**); structured history in **Redshift** (the **[data warehouse](/docs/glossary#term-data-warehouse)**); searchable documents in **OpenSearch**. 3. **Prepare:** **Glue** catalogs and transforms the data (ETL); **Lake Formation** governs who can see what. 4. **Analyze:** **Athena** runs SQL on S3; **EMR** runs Spark and Hadoop clusters; **Managed Service for Apache Flink** processes streams in real time. 5. **Visualize:** **QuickSight** builds dashboards for business users. ## Which service for which question [#which-service-for-which-question] - **SQL on files in S3, no servers, pay per query** → [Athena](/docs/analytics/athena). - **Data warehouse, complex joins and aggregations, BI** → [Redshift](/docs/analytics/redshift). - **Search any field, partial matches, log analytics** → [OpenSearch](/docs/analytics/opensearch). - **Hadoop or Spark clusters for big data** → [EMR](/docs/analytics/emr). - **Dashboards for business users** → [QuickSight](/docs/analytics/quicksight). - **ETL, convert CSV to Parquet, catalog the data** → [Glue](/docs/analytics/glue). - **Build a data lake with fine-grained (row, column) permissions** → [Lake Formation](/docs/analytics/lake-formation). - **Real-time stream processing, or managed Kafka** → [Managed Flink and MSK](/docs/analytics/flink-msk). ## In this group [#in-this-group] ## Exam tips [#exam-tips] - **"Serverless", "least operational overhead", "query data in S3"** → Athena (often with Glue and QuickSight). - **"Data warehouse", "OLAP", "complex analytical queries"** → Redshift. - **"Convert to a columnar format to cut cost"** → Glue job to Parquet or ORC, then Athena. - **"Streaming data"** → Kinesis or MSK to ingest, Flink to process, Firehose to load. ## Common traps [#common-traps] - **"Redshift for transactions (OLTP)."** Redshift is for analytics; use RDS, Aurora or DynamoDB for transactions. - **"Athena loads data first."** Athena queries the files where they are, in S3. ## AWS documentation [#aws-documentation] - [Analytics on AWS](https://aws.amazon.com/big-data/datalakes-and-analytics/) - [What is a data lake?](https://aws.amazon.com/what-is/data-lake/) # AWS Lake Formation (/docs/analytics/lake-formation) ## What it is [#what-it-is] A **[data lake](/docs/glossary#term-data-lake)** is a **central place to keep all your data** for analytics, structured and unstructured, usually in S3. **[AWS Lake Formation](/docs/glossary#term-aws-lake-formation)** is a fully managed service that makes it easy to **set up a data lake in days** and to **govern** it. - **Discover, cleanse, transform and ingest** data into your data lake. - It automates many complex manual steps (collecting, cleansing, moving, cataloguing data…) and **de-duplicates** records (with ML transforms). - Combine **structured and unstructured** data in the data lake. - **Out-of-the-box source blueprints:** S3, RDS, relational and NoSQL databases… - **Fine-grained access control** for your applications: **row, column and cell-level**. - **Built on top of AWS Glue:** it uses Glue crawlers, Glue ETL and the **Glue Data Catalog**.
![AWS Lake Formation: data from S3, RDS, Aurora and on-premises databases is ingested into a Lake Formation data lake stored in S3, with source crawlers, ETL and data prep, the Data Catalog, security settings and access control in one place; Athena, Redshift, EMR and QuickSight read it with row, column and cell-level permissions](/diagrams/analytics-lake-formation.light.svg) ![AWS Lake Formation: data from S3, RDS, Aurora and on-premises databases is ingested into a Lake Formation data lake stored in S3, with source crawlers, ETL and data prep, the Data Catalog, security settings and access control in one place; Athena, Redshift, EMR and QuickSight read it with row, column and cell-level permissions](/diagrams/analytics-lake-formation.dark.svg)
Ingest once, govern access in one place.
## Centralized permissions [#centralized-permissions] Without Lake Formation, securing a data lake means writing S3 bucket policies, IAM policies and per-service settings, and keeping them consistent for Athena, QuickSight, Redshift and EMR separately. With Lake Formation: - You **grant and revoke** permissions on databases, tables, columns and rows **in one place**, much like in a relational database (`GRANT SELECT ON sales (region, amount) TO analysts`). - **Data filters** give **column-level, row-level and cell-level security**. - The permissions are **enforced by the analytics services**: Athena, QuickSight, Redshift Spectrum, EMR and Glue. - You can **share** data with other AWS accounts or a whole AWS Organization, with the same fine-grained control. **LF-Tags** let you grant access by tag at scale. For example, the marketing team's analysts query the customer table in Athena and see every column except `email` and `phone`, and only rows for their own country, while the data science team sees everything. ## Real-world examples [#real-world-examples] - **A hospital group** ingests data from several databases into an S3 data lake with Lake Formation blueprints, and researchers see patient records without names or addresses (column-level security). - **A company with many accounts** keeps one central data lake account and shares specific tables with each business unit's account through Lake Formation. ## Exam tips [#exam-tips] - **"Build a data lake quickly"** → Lake Formation. - **"Centrally manage fine-grained (column, row, cell-level) access to data in the data lake"** → Lake Formation permissions. - **"Share data lake tables across accounts with fine-grained control"** → Lake Formation (cross-account sharing, LF-Tags). - **"De-duplicate records in the data lake"** → Lake Formation / Glue ML transforms (FindMatches). ## Common traps [#common-traps] - **"Use S3 bucket policies for column-level access."** S3 policies work on objects, not columns or rows; use Lake Formation. - **"Lake Formation replaces Glue."** It's built on Glue (catalog, crawlers, ETL) and adds governance. ## Check yourself [#check-yourself] Setting up Lake Formation permissions takes a full data lake to be meaningful, so instead: Register the data lake with Lake Formation and grant column-level permissions on the table: HR gets all columns, other analysts get every column except salary. Athena and QuickSight enforce it. ## AWS documentation [#aws-documentation] - [What is AWS Lake Formation?](https://docs.aws.amazon.com/lake-formation/latest/dg/what-is-lake-formation.html) - [Data filtering and cell-level security](https://docs.aws.amazon.com/lake-formation/latest/dg/data-filtering.html) # Amazon OpenSearch Service (/docs/analytics/opensearch) ## What it is [#what-it-is] **[Amazon OpenSearch Service](/docs/glossary#term-amazon-opensearch-service)** is the successor to Amazon Elasticsearch Service. It runs **OpenSearch** (and legacy Elasticsearch up to 7.10) for **search and analytics**. - In DynamoDB, you can only query by **primary key or indexes**. With OpenSearch, you can **search any field, even partial matches** (full-text search, "contains", fuzzy matching). - It's common to use OpenSearch **as a complement to another database**: the database keeps the data, OpenSearch makes it searchable. - **Two modes:** a managed cluster (a **domain**) or **OpenSearch Serverless** (collections, no cluster to size). - **Data in** from **Data Firehose**, **AWS IoT**, **CloudWatch Logs**, and **OpenSearch Ingestion** pipelines. - **Security** through **Cognito** and **IAM**, **KMS** encryption at rest, **TLS** in transit. - Comes with **OpenSearch Dashboards** for visualization. - **Use cases:** search boxes on websites and apps, log analytics, real-time application monitoring, security analytics. The slides say OpenSearch doesn't natively support SQL and needs a plugin. OpenSearch Service includes **SQL** (and PPL) query support on every domain running OpenSearch or Elasticsearch 6.5 or later, alongside its native JSON query language. ## Pattern: DynamoDB + OpenSearch [#pattern-dynamodb--opensearch]
![OpenSearch with DynamoDB: changes to a DynamoDB table flow through DynamoDB Streams to a Lambda function that indexes the items in OpenSearch; the application searches any field in OpenSearch, then gets the full item from DynamoDB by its ID](/diagrams/analytics-opensearch-dynamodb.light.svg) ![OpenSearch with DynamoDB: changes to a DynamoDB table flow through DynamoDB Streams to a Lambda function that indexes the items in OpenSearch; the application searches any field in OpenSearch, then gets the full item from DynamoDB by its ID](/diagrams/analytics-opensearch-dynamodb.dark.svg)
Search in OpenSearch, read the item from DynamoDB.
1. The application writes items (CRUD) to a **DynamoDB table**. 2. **[DynamoDB Streams](/docs/databases/dynamodb-advanced#stream-processing)** captures every change, and a **Lambda** function indexes it in OpenSearch. 3. To search, the app calls **OpenSearch** ("products containing *wireless*") and gets back the matching item IDs. 4. It then **retrieves the full items** from DynamoDB by ID. Today, an **OpenSearch Ingestion** pipeline with the DynamoDB plugin can replace Streams + Lambda: a managed **zero-ETL** sync (it uses DynamoDB Streams, and point-in-time recovery for the first full copy). ## Patterns: CloudWatch Logs and Kinesis [#patterns-cloudwatch-logs-and-kinesis]
![Four ways to send data to OpenSearch: CloudWatch Logs through a subscription filter to a Lambda function (real time) or to Firehose (near real time), and Kinesis Data Streams to Firehose (near real time) or to a Lambda function (real time)](/diagrams/analytics-opensearch-ingest.light.svg) ![Four ways to send data to OpenSearch: CloudWatch Logs through a subscription filter to a Lambda function (real time) or to Firehose (near real time), and Kinesis Data Streams to Firehose (near real time) or to a Lambda function (real time)](/diagrams/analytics-opensearch-ingest.dark.svg)
Lambda for real time, Firehose for near real time.
- **CloudWatch Logs → subscription filter → Lambda** (managed by AWS) → OpenSearch: **real time**. - **CloudWatch Logs → subscription filter → Data Firehose** → OpenSearch: **near real time** (Firehose buffers). - **Kinesis Data Streams → Data Firehose** (optionally transforming data with Lambda) → OpenSearch: **near real time**. - **Kinesis Data Streams → Lambda** (your code) → OpenSearch: **real time**. ## Real-world examples [#real-world-examples] - **An online shop** keeps its catalogue in DynamoDB and indexes it in OpenSearch, so shoppers can type "red runn" and find "Red running shoes". - **An operations team** streams application logs from CloudWatch Logs to OpenSearch through Firehose and explores errors in OpenSearch Dashboards. ## Exam tips [#exam-tips] - **"Search any field", "full-text search", "partial matches"** → OpenSearch. - **"Make DynamoDB data searchable"** → DynamoDB Streams + Lambda (or OpenSearch Ingestion) to OpenSearch. - **"Real-time log analytics and dashboards"** → CloudWatch Logs subscription filter to OpenSearch. - **"Near real time, managed, no code"** → through Firehose. **"Real time"** → through Lambda. - **"Elasticsearch on AWS"** → Amazon OpenSearch Service. ## Common traps [#common-traps] - **"Use OpenSearch as the primary database."** It's usually a search index next to the real data store. - **"Firehose delivers in real time."** It's near real time (buffered); Lambda is real time. ## Check yourself [#check-yourself] An OpenSearch domain costs about $0.04 an hour for the smallest instance and is easy to forget, so instead: Sync the table to OpenSearch: an OpenSearch Ingestion pipeline with the DynamoDB plugin (or DynamoDB Streams with a Lambda function), search in OpenSearch, and read full items from DynamoDB by ID. Create a CloudWatch Logs subscription filter that sends the logs to OpenSearch through the AWS-managed Lambda function (real time), not through Firehose (near real time). ## AWS documentation [#aws-documentation] - [What is Amazon OpenSearch Service?](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/what-is.html) - [What is Amazon OpenSearch Serverless?](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-overview.html) - [Querying your data with SQL](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/sql-support.html) - [Overview of Amazon OpenSearch Ingestion](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/ingestion.html) - [Using an OpenSearch Ingestion pipeline with DynamoDB](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/configure-client-ddb.html) # Amazon QuickSight (/docs/analytics/quicksight) ## What it is [#what-it-is] **[Amazon QuickSight](/docs/glossary#term-amazon-quicksight)** is a **serverless, machine learning-powered business intelligence (BI)** service to create **interactive dashboards**. - Fast, automatically scalable, **embeddable** in your own applications, with **per-session pricing** for readers. - **Use cases:** business analytics, building visualizations, ad-hoc analysis, getting business insights from data. - **Integrated** with RDS, Aurora, Athena, Redshift, S3 and more. - **In-memory computation** with the **[SPICE](/docs/glossary#term-spice)** engine, if data is **imported** into QuickSight. - **Enterprise edition:** **column-level security (CLS)** and **row-level security (RLS)**, so each user sees only the columns and rows they're allowed to. QuickSight has grown into **AWS Quick**, an AI-powered workspace. The BI dashboards live on as **AWS Quick Sight**, a feature of AWS Quick, and all QuickSight APIs keep working. The exam guide still calls it **Amazon QuickSight**, and so do these notes. ## Integrations [#integrations]
![QuickSight: data from AWS sources such as RDS, Aurora, Redshift, Athena, S3, OpenSearch and Timestream, SaaS apps such as Salesforce and Jira, files and on-premises databases over JDBC is queried directly or imported into the SPICE in-memory engine, and shared as dashboards with users and groups](/diagrams/analytics-quicksight.light.svg) ![QuickSight: data from AWS sources such as RDS, Aurora, Redshift, Athena, S3, OpenSearch and Timestream, SaaS apps such as Salesforce and Jira, files and on-premises databases over JDBC is queried directly or imported into the SPICE in-memory engine, and shared as dashboards with users and groups](/diagrams/analytics-quicksight.dark.svg)
Many sources in, dashboards out.
- **AWS services:** RDS, Aurora, Redshift, Athena, S3, OpenSearch, Timestream. - **SaaS apps:** Salesforce, Jira and others. - **Third-party and on-premises databases** over JDBC, such as Teradata. - **File imports:** XLSX, CSV, JSON, TSV, and log formats (ELF and CLF). For each dataset you choose a **direct query** (always fresh) or **SPICE** (imported into memory: faster, and reused without querying the source each time). ## Dashboards and analyses [#dashboards-and-analyses] - QuickSight has its own **users** (Standard edition) and **groups** (Enterprise edition). They exist **only within QuickSight, not in IAM** (accounts can also sign in through IAM Identity Center). - An **analysis** is where you explore data and build visuals. - A **dashboard**: - is a **read-only snapshot of an analysis** that you can share; - keeps the analysis configuration (filtering, parameters, controls, sort). - You can **share the analysis or the dashboard** with users or groups. - To share a dashboard, you must first **publish** it. - Users who see the dashboard can also **see the underlying data** (limit it with RLS and CLS). ## Real-world examples [#real-world-examples] - **A sales director** opens a QuickSight dashboard each morning built on Athena queries over the sales data lake, with each regional manager seeing only their region's rows (RLS). - **A software company** embeds QuickSight dashboards in its customer portal and pays per reader session. ## Exam tips [#exam-tips] - **"Business intelligence dashboards", "visualize data", "serverless BI"** → QuickSight. - **"Dashboards on data in S3"** → Athena + QuickSight. - **"Users should see only some columns or rows"** → QuickSight Enterprise CLS or RLS (or Lake Formation for the data lake). - **"Fast dashboards with in-memory data"** → import into SPICE. ## Common traps [#common-traps] - **"Manage QuickSight users as IAM users."** QuickSight users and groups are its own (or from an identity provider), not IAM users. - **"QuickSight stores and transforms the data."** It visualizes data; ETL belongs in Glue. ## Check yourself [#check-yourself] QuickSight bills per user per month (with a free trial), so instead: Use QuickSight Enterprise edition with row-level security on the dataset, then publish the dashboard and share it with the managers' group. ## AWS documentation [#aws-documentation] - [What is AWS Quick?](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) - [Importing data into SPICE](https://docs.aws.amazon.com/quicksight/latest/user/spice.html) - [Using row-level security](https://docs.aws.amazon.com/quicksight/latest/user/row-level-security.html) # Amazon Redshift (/docs/analytics/redshift) ## What it is [#what-it-is] **[Amazon Redshift](/docs/glossary#term-amazon-redshift)** is the AWS **data warehouse**. - It's based on **PostgreSQL**, but it's **not for OLTP** (transactions). It's **[OLAP](/docs/glossary#term-olap)**: online analytical processing, for analytics and data warehousing. - **Columnar storage** (instead of row-based) and a **massively parallel** query engine: scans and aggregations over billions of rows are fast. It scales to petabytes. - **Two modes:** **provisioned cluster** or **Redshift Serverless**. - A **SQL interface** (JDBC/ODBC) for queries; BI tools such as **QuickSight** or Tableau connect to it. - **vs Athena:** Redshift is faster for heavy, frequent queries, **joins and aggregations**, because data is loaded and organised (sort keys, distribution) inside the warehouse. Athena is better for occasional, ad-hoc queries on files in S3. ## Cluster and Serverless [#cluster-and-serverless]
![Redshift cluster and Spectrum: a SQL client connects over JDBC or ODBC to the leader node, which plans the query and aggregates results from compute nodes running in parallel; with Spectrum, the cluster hands the part of the query that reads S3 to thousands of Spectrum nodes, so data in S3 is queried without loading it](/diagrams/analytics-redshift-spectrum.light.svg) ![Redshift cluster and Spectrum: a SQL client connects over JDBC or ODBC to the leader node, which plans the query and aggregates results from compute nodes running in parallel; with Spectrum, the cluster hands the part of the query that reads S3 to thousands of Spectrum nodes, so data in S3 is queried without loading it](/diagrams/analytics-redshift-spectrum.dark.svg)
A leader plans, compute nodes work in parallel.
- **Leader node:** receives the query, **plans** it, and **aggregates** the results. Clients only talk to the leader. - **Compute nodes:** **run the query** on their part of the data and send results to the leader. - **Provisioned mode:** choose node types and count in advance; **reserve** nodes for cost savings. - **Redshift Serverless:** capacity is provisioned and scaled for you, and you **pay only when the warehouse is in use**. Good for unpredictable or occasional workloads. ## High availability, snapshots and DR [#high-availability-snapshots-and-dr]
![Redshift snapshots for disaster recovery: an incremental snapshot of the original cluster in us-east-1 is stored in S3 and copied, automatically or manually, to eu-west-1, where it is restored into a new cluster](/diagrams/analytics-redshift-snapshots.light.svg) ![Redshift snapshots for disaster recovery: an incremental snapshot of the original cluster in us-east-1 is stored in S3 and copied, automatically or manually, to eu-west-1, where it is restored into a new cluster](/diagrams/analytics-redshift-snapshots.dark.svg)
Copy snapshots to another Region for disaster recovery.
- **Multi-AZ:** available for provisioned **RA3** (and the newer RG) clusters. Compute runs in **two AZs** behind one endpoint, so the warehouse survives an AZ failure. - **Snapshots** are point-in-time backups of a cluster, **stored internally in S3**. - **Incremental:** only what changed is saved. - **Restore** a snapshot into a **new cluster**. - **Automated snapshots:** about **every 8 hours or every 5 GB per node** of changes (whichever comes first), or on a **schedule**. Retention **1 to 35 days** (default 1 day). - **Manual snapshots:** kept **until you delete them** (or for a retention period you set). - **Cross-Region copy:** configure Redshift to **automatically copy snapshots** (automated or manual) of a cluster **to another Region**, for disaster recovery. ## Loading data into Redshift [#loading-data-into-redshift]
![Loading data into Redshift: Firehose buffers records into S3 and runs COPY; the COPY command loads files from S3 using an IAM role, over the internet or through your VPC with enhanced VPC routing; an EC2 application using JDBC should write in large batches rather than single rows](/diagrams/analytics-redshift-loading.light.svg) ![Loading data into Redshift: Firehose buffers records into S3 and runs COPY; the COPY command loads files from S3 using an IAM role, over the internet or through your VPC with enhanced VPC routing; an EC2 application using JDBC should write in large batches rather than single rows](/diagrams/analytics-redshift-loading.dark.svg)
Large batch inserts are much better than single rows.
**Large inserts are MUCH better** than many small ones. Three common ways: - **[Amazon Data Firehose](/docs/integration/kinesis#amazon-data-firehose):** buffers streaming records into S3, then issues a COPY into Redshift for you. - **S3 with the `COPY` command:** load files from S3 in parallel, using an IAM role attached to the cluster: ```sql copy customer from 's3://mybucket/mydata' iam_role 'arn:aws:iam::123456789012:role/MyRedshiftRole'; ``` The traffic goes over the internet by default. With **[enhanced VPC routing](/docs/glossary#term-enhanced-vpc-routing)**, all `COPY` and `UNLOAD` traffic goes **through your VPC**, so you can use VPC endpoints, security groups and flow logs. - **EC2 application with the JDBC driver:** write data **in batches**. **Zero-ETL integrations** replicate data from **Aurora MySQL and PostgreSQL**, **RDS for MySQL, PostgreSQL and Oracle**, **DynamoDB** and some SaaS apps into Redshift automatically, within seconds, with no pipeline to build. Look for it in questions about "near real-time analytics on transactional data with the least effort". ## Redshift Spectrum [#redshift-spectrum] The diagram at the top of this page shows **[Redshift Spectrum](/docs/glossary#term-redshift-spectrum)** below the cluster. - **Query data that's already in S3 without loading it** into Redshift tables. - You **must have a Redshift cluster** (or Serverless workgroup) available to start the query. - The query is then submitted to **thousands of Redshift Spectrum nodes**, which read S3 in parallel. - You can **join** S3 data (for example years of history) with tables in the warehouse (recent data). Several clusters can query the same S3 data. - Spectrum reads table definitions from the **Glue Data Catalog** (external tables). ## Real-world examples [#real-world-examples] - **A retailer** loads every night's sales into a Redshift cluster with `COPY` from S3, and analysts run reports in QuickSight every morning. - **A finance team** keeps two years of data in Redshift and ten years of history in S3, and joins them with Spectrum without loading the old data. - **A bank** copies Redshift snapshots automatically to a second Region so it can restore the warehouse there after a Regional outage. ## Exam tips [#exam-tips] - **"Data warehouse", "OLAP", "BI on petabytes", "complex joins and aggregations"** → Redshift. - **"Query S3 data from Redshift without loading it"** → Redshift Spectrum. - **"Disaster recovery for Redshift in another Region"** → automated cross-Region snapshot copy. - **"Load data into Redshift efficiently"** → `COPY` from S3 (large batches), or Firehose for streams. - **"COPY traffic must not leave the VPC"** → enhanced VPC routing. - **"Unpredictable, occasional warehouse workloads"** → Redshift Serverless. ## Common traps [#common-traps] - **"Redshift for an OLTP application."** It's an analytics warehouse; use RDS or Aurora. - **"Insert rows one at a time from an app."** Very slow; batch them or use COPY. - **"Spectrum works without a cluster."** It needs a Redshift cluster or Serverless; for no warehouse at all, use Athena. - **"Restore a snapshot into the existing cluster."** A restore creates a new cluster. ## Check yourself [#check-yourself] A Redshift cluster costs from about $0.25 an hour, and Serverless bills at least 60 seconds of capacity each time it runs, so instead: Enable cross-Region snapshot copy for the cluster, so automated (and manual) snapshots are copied to the DR Region, and restore a new cluster from them when needed. Use Redshift Spectrum: define external tables over the S3 data in the Glue Data Catalog and join them with the Redshift tables in one query. ## AWS documentation [#aws-documentation] - [Amazon Redshift system architecture](https://docs.aws.amazon.com/redshift/latest/dg/c_high_level_system_architecture.html) - [What is Amazon Redshift Serverless?](https://docs.aws.amazon.com/redshift/latest/mgmt/serverless-whatis.html) - [Multi-AZ deployment](https://docs.aws.amazon.com/redshift/latest/mgmt/managing-cluster-multi-az.html) - [Amazon Redshift snapshots and backups](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html) - [Enhanced VPC routing](https://docs.aws.amazon.com/redshift/latest/mgmt/enhanced-vpc-routing.html) - [Zero-ETL integrations](https://docs.aws.amazon.com/redshift/latest/mgmt/zero-etl-using.html) - [Amazon Redshift Spectrum](https://docs.aws.amazon.com/redshift/latest/dg/c-using-spectrum.html) # Blocking an IP address (/docs/architecture/blocking-ip-addresses) ## The layers you can use [#the-layers-you-can-use]
![Where to block an IP address: AWS WAF IP set rules and CloudFront geo restriction act at the edge; in the VPC, the network ACL of the public subnet can deny an IP, but behind CloudFront it only sees CloudFront IPs; the ALB has its own security group, and the EC2 instances in the private subnet allow only the ALB security group](/diagrams/arch-block-ip.light.svg) ![Where to block an IP address: AWS WAF IP set rules and CloudFront geo restriction act at the edge; in the VPC, the network ACL of the public subnet can deny an IP, but behind CloudFront it only sees CloudFront IPs; the ALB has its own security group, and the EC2 instances in the private subnet allow only the ALB security group](/diagrams/arch-block-ip.dark.svg)
Block the client where you can still see its address.
Start with a client reaching a public EC2 instance directly, then add each layer: 1. **Instance only.** - The **[network ACL](/docs/vpc/nacl-vs-security-groups#network-acls)** of the subnet can **deny** the IP: NACLs have deny rules. - The **security group** can't: it only has **allow** rules. You can allow-list a known set of IPs, but not block one. - Optional **firewall software** on the instance can also block it (costs CPU). 2. **With an ALB.** The ALB **terminates the connection**, so the instances (now private, with an SG allowing only the ALB's SG) only see the ALB. Block the IP with the **NACL** of the ALB's subnets. The client's IP is in the `X-Forwarded-For` header for the app. 3. **With an NLB.** Traffic passes through with the client IP preserved. Block with the **NACL**; NLBs also support security groups now. 4. **ALB + [AWS WAF](/docs/security/waf-shield-firewall-manager#aws-waf).** Attach a web ACL to the ALB with an **IP set** rule (and rate-based or geo rules). WAF costs a little but filters at layer 7 with much more flexibility. 5. **CloudFront + WAF.** With CloudFront in front, the ALB sees **CloudFront's IPs**, so a **NACL can't block the client**: it's **not helpful** here. Instead: - attach **WAF to the CloudFront distribution** with an IP set rule; - use **[CloudFront geo restriction](/docs/edge/cloudfront#geo-restriction)** to block whole countries; - let the ALB security group allow only CloudFront (the AWS-managed prefix list for CloudFront origin-facing IPs). **CloudFront VPC origins** let the ALB, NLB or EC2 instances sit in **private subnets** with no public entry at all, so CloudFront (with WAF) becomes the only way in. See [CloudFront VPC origins](/docs/edge/cloudfront#alb-or-ec2-as-an-origin). ## Real-world examples [#real-world-examples] - **A ticket site** blocks a scraper's IP range with a WAF IP set on its CloudFront distribution and adds a rate-based rule of 2,000 requests per 5 minutes per IP. ## Exam tips [#exam-tips] - **"Block a specific IP address at the subnet level"** → **NACL deny rule**. - **"Security groups can deny an IP"** → false: SGs only allow. - **"Block IPs with CloudFront in front"** → **WAF on CloudFront** (IP set); NACLs only see CloudFront IPs. - **"Block a country"** → CloudFront geo restriction or a WAF geo match rule. ## Common traps [#common-traps] - **"Add the attacker's IP to the ALB's NACL when CloudFront is in front."** The NACL sees CloudFront edge IPs, not the client. Use WAF on CloudFront. - **"Remove the IP from the security group to block it."** If the SG allows `0.0.0.0/0`, everyone is allowed; SGs can't express "everyone but this IP". ## Check yourself [#check-yourself] Create an AWS WAF web ACL with an IP set rule that blocks the address (and maybe a rate-based rule for the login path), and associate it with the CloudFront distribution. A NACL wouldn't work, because traffic reaches the VPC from CloudFront's IPs. ## AWS documentation [#aws-documentation] - [Control subnet traffic with network access control lists](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) - [IP set match rule statement (AWS WAF)](https://docs.aws.amazon.com/waf/latest/developerguide/waf-rule-statement-type-ipset-match.html) - [Restrict the geographic distribution of your content](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/georestrictions.html) - [Use the AWS-managed prefix list for CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/LocationsOfEdgeServers.html) # Caching strategies (/docs/architecture/caching-strategies) ## Where you can cache [#where-you-can-cache]
![Caching layers along a request: CloudFront caches at the edge, API Gateway caches responses, the application caches in ElastiCache or DAX in front of the database; caching near the user is faster and cheaper but may serve stale data, caching near the data is fresher but costs more work](/diagrams/arch-caching-layers.light.svg) ![Caching layers along a request: CloudFront caches at the edge, API Gateway caches responses, the application caches in ElastiCache or DAX in front of the database; caching near the user is faster and cheaper but may serve stale data, caching near the data is fresher but costs more work](/diagrams/arch-caching-layers.dark.svg)
Every layer can answer before the database is asked.
A request travels from the client to the database. Each layer on the way can keep a copy of the answer: - **[CloudFront](/docs/edge/cloudfront)** at the **edge**, closest to users, for static files and cacheable API responses. Static content in S3 can go straight from CloudFront to S3. - **API Gateway caching**, per stage, in the Region: whole responses for a TTL (default 300 seconds, up to 3,600). - **Application caches:** **[ElastiCache](/docs/databases/elasticache#caching-strategies)** (Valkey, Redis OSS or Memcached) for any database or computed result, **[DAX](/docs/databases/dynamodb-advanced#dynamodb-accelerator-dax)** for DynamoDB. - **The database** itself: read replicas spread the reads but aren't a cache. ## The trade-offs [#the-trade-offs] The further toward the user you cache, the more you save, but the more care you need: - **Latency:** an edge hit answers in milliseconds near the user; a database query may cross the world. - **Cost and computation:** every hit at an outer layer is a request the app servers and database don't pay for. - **Network:** data served from the edge doesn't travel from your Region. - **TTL and freshness:** a long TTL means more hits but **staler data**; dynamic or per-user data needs short TTLs or no cache. Invalidations (CloudFront) or write-through updates (ElastiCache) help. - **Security:** never cache per-user responses under a shared key. ## Real-world examples [#real-world-examples] - **A sports results site** caches the scoreboard API at CloudFront for 5 seconds: millions of fans, but the origin sees one request per edge location every 5 seconds. - **A shop** caches product pages for an hour at the edge, product data in ElastiCache for 10 minutes, and never caches the cart. ## Exam tips [#exam-tips] - **"Static content, global users, reduce load on the origin"** → CloudFront. - **"Same API responses requested repeatedly"** → API Gateway caching (or CloudFront in front of the API). - **"Database read load, sub-millisecond reads"** → ElastiCache; **"DynamoDB, microseconds, no code change"** → DAX. - **"Users see old data after an update"** → shorter TTLs, CloudFront invalidations, or write-through caching. ## Common traps [#common-traps] - **"Read replicas are a cache."** They copy the whole database and still run queries; a cache stores answers. - **"Cache everything at the edge."** Per-user and fast-changing data must not be cached, or only very briefly. ## AWS documentation [#aws-documentation] - [Caching overview](https://aws.amazon.com/caching/) - [Caching strategies for ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Strategies.html) - [Manage how long content stays in the cache (CloudFront)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) - [Cache settings for REST APIs in API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-caching.html) # Event processing (/docs/architecture/event-processing) ## Lambda with SQS, SQS FIFO and SNS [#lambda-with-sqs-sqs-fifo-and-sns]
![Lambda with queues and topics: Lambda polls an SQS queue, and failed messages return to the queue and are retried until they move to the queue's dead-letter queue; with SQS FIFO, messages are processed in order and a failing message blocks its message group until it succeeds or moves to the DLQ; SNS invokes Lambda asynchronously, Lambda retries, then sends the event to an SQS dead-letter queue](/diagrams/arch-lambda-queues.light.svg) ![Lambda with queues and topics: Lambda polls an SQS queue, and failed messages return to the queue and are retried until they move to the queue's dead-letter queue; with SQS FIFO, messages are processed in order and a failing message blocks its message group until it succeeds or moves to the DLQ; SNS invokes Lambda asynchronously, Lambda retries, then sends the event to an SQS dead-letter queue](/diagrams/arch-lambda-queues.dark.svg)
Where the retries happen, and where failures end up.
- **SQS + Lambda:** Lambda **polls** the queue. A message that fails becomes visible again after the visibility timeout and is **retried**; after `maxReceiveCount` attempts, the queue moves it to its **[dead-letter queue](/docs/integration/sqs)** (set on the **SQS** queue). - **SQS FIFO + Lambda:** messages are processed **in order** within each message group. A failing message is retried and **blocks its group** until it succeeds or moves to the DLQ. - **SNS + Lambda:** SNS invokes Lambda **asynchronously**. Lambda **retries** (twice by default), then sends the event to a DLQ (an SQS queue or SNS topic) or an on-failure destination, set on the **Lambda** side. ## Fan-out: one message, many queues [#fan-out-one-message-many-queues] - **Option 1:** the application **puts the message into each SQS queue** itself. If it crashes between two puts, the queues disagree, and every new queue means a code change. - **Option 2, fan-out:** the application publishes **once to an SNS topic**, and every subscribed queue gets a copy. Add a consumer by adding a subscription. See [SNS + SQS fan-out](/docs/integration/sns-fan-out). ## S3 event notifications [#s3-event-notifications] - Events such as `s3:ObjectCreated`, `s3:ObjectRemoved`, `s3:ObjectRestore`, `s3:Replication`… - **Filter** on the object name (prefix and suffix, for example `*.jpg`). - Use case: **generate thumbnails** of images uploaded to S3. - You can create **as many S3 events as you want**. - Targets: SNS, SQS (standard queues), Lambda. - Events are usually delivered **in seconds**, but sometimes take **a minute or longer**. ### S3 events with Amazon EventBridge [#s3-events-with-amazon-eventbridge] Send **all** the bucket's events to **[EventBridge](/docs/integration/eventbridge)**, then use rules: - **advanced filtering** with JSON rules (metadata, object size, name…); - **many destinations**: Step Functions, Kinesis Data Streams and Firehose, SQS FIFO, and many more AWS services; - EventBridge features: **archive and replay** events, reliable delivery. See [S3 events with Amazon EventBridge](/docs/s3/event-notifications#s3-events-with-amazon-eventbridge). ## EventBridge: intercepting API calls [#eventbridge-intercepting-api-calls]
![Intercepting API calls: a user calls DeleteTable on DynamoDB; CloudTrail logs the API call and sends it as an event to EventBridge, where a rule matches it and alerts the team through Amazon SNS](/diagrams/arch-eventbridge-api-call.light.svg) ![Intercepting API calls: a user calls DeleteTable on DynamoDB; CloudTrail logs the API call and sends it as an event to EventBridge, where a rule matches it and alerts the team through Amazon SNS](/diagrams/arch-eventbridge-api-call.dark.svg)
React to any API call in your account.
**[CloudTrail](/docs/management/cloudtrail)** records **every API call** in the account and delivers it to EventBridge as an event. A rule can match one call (here `DeleteTable` on DynamoDB) and alert through SNS, or start a Lambda function to fix things. ## API Gateway: AWS service integration [#api-gateway-aws-service-integration]
![API Gateway service integration: clients send requests to API Gateway, which writes them straight to Kinesis Data Streams without a Lambda function; Data Firehose reads the records, batches them and delivers JSON files to Amazon S3](/diagrams/arch-apigw-kinesis.light.svg) ![API Gateway service integration: clients send requests to API Gateway, which writes them straight to Kinesis Data Streams without a Lambda function; Data Firehose reads the records, batches them and delivers JSON files to Amazon S3](/diagrams/arch-apigw-kinesis.dark.svg)
An HTTPS front door for a stream, no code.
**[API Gateway](/docs/serverless/api-gateway#integrations)** can call AWS services directly (here Kinesis `PutRecord`), with no Lambda in between. You get API Gateway's features (authentication, throttling, API keys, usage plans) in front of the service without exposing AWS credentials to clients. ## Real-world examples [#real-world-examples] - **An order system** publishes `OrderPlaced` to one SNS topic; the shipping, invoicing and analytics queues each get a copy, and a fourth team subscribes later without touching the order code. - **A security team** alerts on `DeleteBucket`, `StopLogging` and `DeleteTable` calls with EventBridge rules on CloudTrail events. ## Exam tips [#exam-tips] - **"Send the same message to several services reliably"** → SNS topic with SQS subscriptions (**fan-out**). - **"Order matters and messages must not be lost when Lambda fails"** → SQS FIFO + Lambda, with a DLQ. - **"React to object uploads"** → S3 event notifications; **"advanced filtering, many targets, replay"** → S3 → EventBridge. - **"Alert when someone calls a specific API"** → CloudTrail → EventBridge rule → SNS. - **"Expose Kinesis (or SQS, DynamoDB) to clients over HTTPS without Lambda"** → API Gateway AWS service integration. ## Common traps [#common-traps] - **"Set the DLQ on Lambda for an SQS trigger."** For SQS sources, the DLQ belongs to the **queue** (redrive policy). Lambda's own DLQ or destinations apply to **asynchronous** invocations, such as from SNS or S3. - **"S3 notifications go to SQS FIFO."** Not directly; use EventBridge. - **"S3 events are instant."** Usually seconds, sometimes a minute or more. ## Check yourself [#check-yourself] Publish once to an SNS topic and subscribe the three SQS queues (fan-out), or send the S3 upload event to the SNS topic. Each queue gets every message, and adding a fourth service needs no code change. Make sure CloudTrail is on, then create an EventBridge rule matching CloudTrail events with source `aws.dynamodb` and event name `DeleteTable`, targeting an SNS topic the team subscribes to. ## AWS documentation [#aws-documentation] - [Using Lambda with Amazon SQS](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html) - [Error handling and automatic retries in Lambda (asynchronous invocation)](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async-error-handling.html) - [Amazon S3 event notifications](https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventNotifications.html) - [Tutorial: Create an Amazon API Gateway REST API as an Amazon Kinesis proxy](https://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-kinesis.html) # Highly available EC2 instance (/docs/architecture/highly-available-ec2) Some apps can only run as **one instance** (a license server, a legacy app) and are reached at **one public IP**. How do you keep it available? ## A standby instance and Lambda [#a-standby-instance-and-lambda]
![A highly available EC2 instance with a standby: users reach the active instance through an Elastic IP; a CloudWatch alarm or EventBridge rule watches its health and triggers a Lambda function, which starts the standby instance and moves the Elastic IP to it](/diagrams/arch-ha-ec2-standby.light.svg) ![A highly available EC2 instance with a standby: users reach the active instance through an Elastic IP; a CloudWatch alarm or EventBridge rule watches its health and triggers a Lambda function, which starts the standby instance and moves the Elastic IP to it](/diagrams/arch-ha-ec2-standby.dark.svg)
Watch the active instance, move the address on failure.
- Users reach the public instance through an **[Elastic IP](/docs/compute/ip-addressing#elastic-ip-addresses)**. - A **CloudWatch alarm** (on a metric or status check) or an **EventBridge** rule watches it. - On failure it invokes **Lambda**, which **starts the standby instance** and **attaches the Elastic IP** to it. ## An Auto Scaling group of one [#an-auto-scaling-group-of-one] - An **ASG** with **min 1, max 1, desired 1**, across **at least 2 AZs**. - If the instance fails, the ASG launches a **replacement**, possibly in the other AZ. - The instance's **user data** attaches the Elastic IP, found by **tag**, when it boots. - The instance needs an **IAM role** that allows the API calls to attach the Elastic IP. ## Keeping the EBS data [#keeping-the-ebs-data]
![A highly available EC2 instance with an Auto Scaling group of minimum, maximum and desired 1 across two AZs: the instance's user data attaches the Elastic IP; when the instance in AZ A is terminated, a lifecycle hook snapshots its EBS volume with tags; the replacement in AZ B gets a new volume from that snapshot through the launch lifecycle hook and takes the Elastic IP](/diagrams/arch-ha-ec2-asg.light.svg) ![A highly available EC2 instance with an Auto Scaling group of minimum, maximum and desired 1 across two AZs: the instance's user data attaches the Elastic IP; when the instance in AZ A is terminated, a lifecycle hook snapshots its EBS volume with tags; the replacement in AZ B gets a new volume from that snapshot through the launch lifecycle hook and takes the Elastic IP](/diagrams/arch-ha-ec2-asg.dark.svg)
Carry the disk across AZs with a snapshot.
An EBS volume is tied to its AZ, so the replacement in another AZ can't just reattach it: - An ASG **terminate lifecycle hook** takes an **EBS snapshot** (with tags) before the instance goes away. - An ASG **launch lifecycle hook** creates a new volume from that snapshot in the new AZ and attaches it to the replacement. For hardware failures within one AZ, EC2 **automatic instance recovery** (simplified automatic recovery is on by default for supported instances, or a CloudWatch alarm action) moves the instance to new hardware and keeps its instance ID, private IPs, Elastic IP and EBS volumes. It doesn't help if the AZ fails. See [EC2 instance recovery](/docs/management/cloudwatch-alarms#ec2-instance-recovery). ## Real-world examples [#real-world-examples] - **A license server** that clients reach at a fixed IP runs in an ASG of one across two AZs; its user data reattaches the Elastic IP tagged `license-server`, and its config lives on EFS so no snapshot dance is needed. ## Exam tips [#exam-tips] - **"Single instance, must survive an AZ failure, fixed public IP"** → ASG min/max/desired 1 across 2+ AZs + user data that attaches the Elastic IP (with an instance role). - **"Automatically recover an instance after a hardware failure, same IP"** → EC2 automatic recovery (CloudWatch `StatusCheckFailed_System`). - **"Run custom actions when an ASG launches or terminates an instance"** → **lifecycle hooks**. ## Common traps [#common-traps] - **"Attach the same EBS volume in the other AZ."** EBS volumes are AZ-bound; use a snapshot (or keep the data on EFS). - **"An ASG of one gives zero downtime."** A replacement takes minutes to launch; it's high availability, not fault tolerance. ## AWS documentation [#aws-documentation] - [Amazon EC2 Auto Scaling lifecycle hooks](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html) - [Automatic instance recovery](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-recover.html) - [Associate an Elastic IP address with an instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-eips.html) # High performance computing (HPC) (/docs/architecture/hpc) ## Why HPC in the cloud [#why-hpc-in-the-cloud] - The cloud is a great place for HPC: you can create a **very large number of resources** in no time. - You **speed up time to results** by adding more resources. - You **pay only** for the systems you use. - Workloads: genomics, computational chemistry, financial risk modeling, weather prediction, machine learning, deep learning, autonomous driving. Which services help? By job:
![AWS services for high performance computing: transfer data with Direct Connect or DataSync; compute on CPU or GPU EC2 instances in a cluster placement group, with Spot, and an Elastic Fabric Adapter for MPI with OS-bypass on Linux; store data on FSx for Lustre or EBS io2 Block Express; automate with AWS Batch multi-node parallel jobs and AWS ParallelCluster or AWS PCS](/diagrams/arch-hpc.light.svg) ![AWS services for high performance computing: transfer data with Direct Connect or DataSync; compute on CPU or GPU EC2 instances in a cluster placement group, with Spot, and an Elastic Fabric Adapter for MPI with OS-bypass on Linux; store data on FSx for Lustre or EBS io2 Block Express; automate with AWS Batch multi-node parallel jobs and AWS ParallelCluster or AWS PCS](/diagrams/arch-hpc.dark.svg)
Move the data, compute, store, automate.
## Data management and transfer [#data-management-and-transfer] - **[AWS Direct Connect](/docs/vpc/direct-connect):** move GB/s of data to the cloud over a private, secure network. - **[Snowball](/docs/migration/snow-family):** move petabytes of data to the cloud offline. - **[AWS DataSync](/docs/migration/datasync):** move large amounts of data between on-premises and S3, EFS or FSx. **Snowmobile** (the 100 PB truck) is no longer offered, and **Snowball Edge** is closed to new customers, with support ending on 31 December 2026. For offline transfers AWS now points to the **AWS Data Transfer Terminal** and partners. See [large data transfers](/docs/migration/large-data-transfer). ## Compute and networking [#compute-and-networking] - **EC2 instances:** CPU optimized or GPU optimized ([instance types](/docs/compute/instance-types)); **Spot Instances and Spot Fleets** for cost savings, with Auto Scaling. - **EC2 placement groups:** a **[cluster placement group](/docs/compute/placement-groups#cluster)** puts instances on the same rack in one AZ for the lowest latency and highest network throughput between them. - **Enhanced networking (SR-IOV):** higher bandwidth, higher packets per second (PPS), lower latency, at no extra cost. - **Elastic Network Adapter (ENA):** up to 100 Gbps; used by every Nitro instance. - **Intel 82599 VF:** up to 10 Gbps, on older instance types: **legacy**. - **[Elastic Fabric Adapter](/docs/glossary#term-elastic-fabric-adapter-efa) (EFA):** an ENA with extra powers for **HPC** and machine learning. - Great for **inter-node communication** in **tightly coupled** workloads. - Uses the **Message Passing Interface (MPI)** standard (and NCCL for ML). - **Bypasses the operating system** (OS-bypass) to give low-latency, reliable transport. - The OS-bypass part works on **Linux**; on Windows an EFA acts as a plain ENA (except for media apps built with the AWS CDI SDK). ## Storage [#storage] - **Instance-attached storage:** - **[EBS](/docs/storage/ebs-volume-types):** scales up to 256,000 IOPS with **io2 Block Express**. - **[Instance store](/docs/storage/instance-store):** millions of IOPS, attached to the host, very low latency (data is lost when the instance stops). - **Network storage:** - **Amazon S3:** large objects, but not a file system. - **Amazon EFS:** IOPS scale with the throughput mode (elastic or provisioned). - **[FSx for Lustre](/docs/storage/fsx#fsx-for-lustre):** an HPC-optimized distributed file system with millions of IOPS, **linked to S3**. ## Automation and orchestration [#automation-and-orchestration] - **[AWS Batch](/docs/compute/batch):** supports **multi-node parallel jobs**, so one job can span several EC2 instances; it schedules jobs and launches instances for you. - **AWS ParallelCluster:** an open-source, AWS-supported cluster management tool to deploy HPC on AWS. - Configured with **text files**. - Automates the creation of the VPC, subnets, cluster type and instance types. - Can turn on **EFA** on the cluster for better network performance. AWS now recommends **AWS Parallel Computing Service (AWS PCS)**, a **managed Slurm** service, for new HPC clusters; ParallelCluster is still supported but you run it yourself. ParallelCluster dropped AWS Batch as a scheduler from version 3.16 (Slurm remains). ## Real-world examples [#real-world-examples] - **A weather agency** runs a forecast model on 200 `hpc7a` instances with EFA in a cluster placement group, reads input from FSx for Lustre linked to an S3 bucket, and deletes the cluster when the run ends. ## Exam tips [#exam-tips] - **"Tightly coupled HPC, MPI, lowest latency between nodes"** → **EFA** + **cluster placement group**. - **"High-performance file system for HPC, data in S3"** → **FSx for Lustre**. - **"Enhanced networking, up to 100 Gbps"** → **ENA**. - **"Run batch jobs across many instances"** → **AWS Batch** (multi-node parallel jobs). - **"Deploy and manage an HPC cluster with a scheduler"** → **ParallelCluster** (or AWS PCS for a managed Slurm). ## Common traps [#common-traps] - **"EFA works the same on Windows."** OS-bypass is for Linux. - **"Spread placement group for HPC."** Spread is for availability; HPC wants **cluster**. - **"Use EFS for the highest HPC throughput."** FSx for Lustre is the HPC file system. ## AWS documentation [#aws-documentation] - [Elastic Fabric Adapter for AI/ML and HPC workloads](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) - [Enhanced networking on Amazon EC2 instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking.html) - [What is AWS ParallelCluster](https://docs.aws.amazon.com/parallelcluster/latest/ug/what-is-aws-parallelcluster.html) - [What is AWS Parallel Computing Service?](https://docs.aws.amazon.com/pcs/latest/userguide/what-is-service.html) - [Multi-node parallel jobs (AWS Batch)](https://docs.aws.amazon.com/batch/latest/userguide/multi-node-parallel-jobs.html) # Immutable infrastructure (/docs/architecture/immutable-infrastructure) Immutable infrastructure is on the exam guide's list of concepts (Domain 2) but not in the course slides. This page is written from the AWS documentation (Well-Architected best practice REL08-BP04). ## What it is [#what-it-is] **[Immutable infrastructure](/docs/glossary#term-immutable-infrastructure)** means **no updates, security patches or configuration changes happen in place** on production resources. When something must change, you **build new resources with the change**, test them, move traffic to them and throw the old ones away. - **Mutable (the old way):** SSH into the servers and patch them. Over months each server drifts a little from the others, and nobody knows exactly what's on them. - **Immutable:** servers are like cattle, not pets. Version 2 is a new image on new instances; version 1 is deleted. ## Why it helps [#why-it-helps] - **Consistency:** every environment runs the same tested image, so testing is simpler. - **No configuration drift:** resources are always in a known, version-controlled state. - **Atomic deployments:** a deployment either completes or nothing changes. - **Fast, safe rollback:** the previous version still exists; switch back to it. - **Better security:** with no in-place changes, you can turn off SSH and remote access entirely. ## How to do it on AWS [#how-to-do-it-on-aws]
![Immutable infrastructure with a blue/green switch: EC2 Image Builder bakes and tests AMI v2, which goes into a new launch template for a new green Auto Scaling group; the load balancer shifts traffic from the blue group on AMI v1 to the green group, and the blue group is drained and terminated instead of being patched in place](/diagrams/arch-immutable.light.svg) ![Immutable infrastructure with a blue/green switch: EC2 Image Builder bakes and tests AMI v2, which goes into a new launch template for a new green Auto Scaling group; the load balancer shifts traffic from the blue group on AMI v1 to the green group, and the blue group is drained and terminated instead of being patched in place](/diagrams/arch-immutable.dark.svg)
Build new, switch traffic, delete old.
- **Prebake images:** **[EC2 Image Builder](/docs/glossary#term-ec2-image-builder)** pipelines build, patch, test and distribute **[golden AMIs](/docs/compute/ami#golden-amis-and-fast-launches)** (and container images) on a schedule. - **Infrastructure as code:** **[CloudFormation](/docs/management/cloudformation)** (or the CDK) declares every resource, stored in source control. A change is a new template version, not a console click. - **Deployment patterns:** - **[Blue/green](/docs/glossary#term-blue-green-deployment):** a full new fleet (green) runs beside the old one (blue); switch traffic all at once or gradually (ALB weighted target groups, **Route 53 weighted records**), then delete blue. **CodeDeploy** and **Elastic Beanstalk** support it. - **Canary:** send a small share of users to the new version, watch errors, then roll out further or roll back. CodeDeploy supports canary configurations (including for Lambda and ECS). - **Auto Scaling instance refresh:** replace instances in an ASG with ones from a new launch template, in batches. - **Detect drift:** **CloudFormation drift detection** and **[AWS Config](/docs/management/config)** rules find anything changed by hand. - **Disallow in-place changes:** IAM policies (and SCPs) that stop people modifying running production resources. Containers and Lambda are immutable by design: each deployment is a new image or a new function version. ## Real-world examples [#real-world-examples] - **A bank** rebuilds its golden AMI with EC2 Image Builder every week, runs its security tests in the pipeline, and rolls the new AMI out with an ASG instance refresh. Nobody has SSH access to production. ## Exam tips [#exam-tips] - **"Avoid configuration drift, replace instead of patching"** → immutable infrastructure: new AMI + new instances. - **"Automate building and patching AMIs"** → **EC2 Image Builder**. - **"Deploy with near-zero downtime and instant rollback"** → **blue/green** (CodeDeploy, Elastic Beanstalk, Route 53 weighted). - **"Test a new version on a small share of traffic first"** → **canary** deployment. - **"Find resources changed outside CloudFormation"** → **drift detection**. ## Common traps [#common-traps] - **"Use Systems Manager Patch Manager on production servers"** when the question asks for **immutable** infrastructure. Patching in place is mutable; patch the image and replace the instances. - **"Blue/green halves the cost."** For a while you run **both** fleets; it costs more during the switch. ## Check yourself [#check-yourself] Build a patched golden AMI each month with an EC2 Image Builder pipeline, put it in a new launch template version, and replace the instances (an ASG instance refresh, or a blue/green switch behind the ALB). Roll back by going back to the previous launch template. ## AWS documentation [#aws-documentation] - [REL08-BP04 Deploy using immutable infrastructure](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_tracking_change_management_immutable_infrastructure.html) - [What is EC2 Image Builder?](https://docs.aws.amazon.com/imagebuilder/latest/userguide/what-is-image-builder.html) - [Use an instance refresh to update instances in an Auto Scaling group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-instance-refresh.html) - [Detect unmanaged configuration changes with drift detection](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html) # Architecture Patterns (/docs/architecture) Most SAA-C03 questions are short stories: a company, a workload, a problem and four architectures. This group walks through the stories the course tells, from a one-instance website to serverless apps, and the principles behind them. Each page ends with the exam keywords that point to that pattern. ## How to read a scenario question [#how-to-read-a-scenario-question] 1. **Find the job.** What must the system do: serve a website, process uploads, store sessions, survive an AZ failure? 2. **Find the qualifier.** It usually decides between two working answers: - **"most cost-effective"** → serverless or managed, Spot or Savings Plans, caching, S3 storage classes; - **"least operational overhead"** → managed services (Aurora, Fargate, Lambda, DynamoDB) over self-managed EC2; - **"highly available"** → Multi-AZ, a load balancer and an Auto Scaling group across at least two AZs; - **"fault tolerant" or "no downtime"** → enough capacity left after losing an AZ, active-active; - **"lowest latency for global users"** → CloudFront, Global Accelerator, DynamoDB global tables, Aurora Global Database; - **"decouple"** → SQS, SNS, EventBridge between the parts. 3. **Find the constraints.** "Without changing the application", "within 15 minutes", "must not traverse the internet", "existing on-premises Active Directory". A constraint rules out answers that otherwise work. 4. **Eliminate.** Two answers are usually wrong on a fact (a service that can't do it). Of the last two, pick the one that meets the qualifier with the fewest moving parts. ## The pattern catalog [#the-pattern-catalog] ### Classic web apps [#classic-web-apps] ### Serverless apps [#serverless-apps] ### Building blocks [#building-blocks] ### Principles [#principles] ## Patterns that come back everywhere [#patterns-that-come-back-everywhere] - **Stateless compute, state elsewhere.** Keep sessions in ElastiCache or DynamoDB and files in S3 or EFS, so any instance (or Lambda) can serve any request and you can scale out freely. - **Load balancer + Auto Scaling group across AZs** is the default answer for highly available EC2. - **Managed over self-managed** whenever the question cares about operational overhead. - **Cache in front of what is slow or expensive:** CloudFront, API Gateway caching, ElastiCache, DAX. - **Queues and topics between parts** so one part can fail or slow down without taking the others with it. - **Least privilege between tiers:** security groups that reference each other. ## AWS documentation [#aws-documentation] - [AWS Architecture Center](https://aws.amazon.com/architecture/) - [AWS Well-Architected Framework](https://docs.aws.amazon.com/wellarchitected/latest/framework/welcome.html) - [AWS Solutions Library](https://aws.amazon.com/solutions/) # Microservices and offloading downloads (/docs/architecture/microservices) ## Microservices [#microservices] We want to move to a **microservice architecture**: - many services talk to each other **directly through REST APIs**; - each service can have its **own architecture**, in whatever form and shape suits it; - each service gets a **leaner development lifecycle**: its own team, deployments and scaling.
![Microservices: users resolve each service name with Route 53 and call it over HTTPS; service1 runs on ECS behind an ALB with DynamoDB, service2 is API Gateway and Lambda with ElastiCache, and service3 is an EC2 Auto Scaling group behind an ALB with RDS; each service is built in the way that suits it](/diagrams/arch-microservices.light.svg) ![Microservices: users resolve each service name with Route 53 and call it over HTTPS; service1 runs on ECS behind an ALB with DynamoDB, service2 is API Gateway and Lambda with ElastiCache, and service3 is an EC2 Auto Scaling group behind an ALB with RDS; each service is built in the way that suits it](/diagrams/arch-microservices.dark.svg)
Each service picks its own building blocks.
## Talking between services [#talking-between-services] - You're free to design each microservice the way you want. - **Synchronous** patterns: **API Gateway**, **load balancers**. The caller waits for the answer. - **Asynchronous** patterns: **[SQS](/docs/integration/sqs)**, **[Kinesis](/docs/integration/kinesis)**, **[SNS](/docs/integration/sns)**, Lambda triggered by S3 events (and EventBridge). The caller hands off the work and carries on, so a slow or failed service doesn't block the others. ## The challenges [#the-challenges] - Repeated overhead to create each new microservice. - Hard to optimize server density and utilization. - The complexity of running many versions of many microservices at once. - Client-side code that must integrate with many separate services. **Serverless patterns solve some of these:** - API Gateway and Lambda **scale automatically** and you **pay per use**, so a little-used service costs little. - You can easily **clone an API** and reproduce whole environments. - API Gateway can **generate client SDKs** from its OpenAPI (Swagger) definition. ## Offloading software updates [#offloading-software-updates] An application on EC2 distributes **software updates** now and then. When a new update comes out, a flood of requests downloads it and the traffic is very costly. We **don't want to change the application**, but we want to cut cost and CPU.
![Offloading software updates: CloudFront is added in front of the existing load balancer; it caches the static update files at the edge, so only cache misses reach the ALB and the EC2 Auto Scaling group, which reads the files from Amazon EFS and can run fewer instances](/diagrams/arch-software-updates.light.svg) ![Offloading software updates: CloudFront is added in front of the existing load balancer; it caches the static update files at the edge, so only cache misses reach the ALB and the EC2 Auto Scaling group, which reads the files from Amazon EFS and can run fewer instances](/diagrams/arch-software-updates.dark.svg)
Put a CDN in front; leave the app alone.
Put **[CloudFront](/docs/edge/cloudfront)** in front of the ALB: - **no change** to the architecture or the application; - CloudFront **caches the update files at the edge**: they're static and never change, a perfect fit; - the EC2 instances aren't serverless, but **CloudFront is**, and it scales for you; - the ASG scales out much less, which **saves a lot on EC2**, on availability effort and on network cost (data from CloudFront to users is cheaper than from EC2, and origin fetches to CloudFront are free). It's an easy way to make an existing application more scalable and cheaper. ## Real-world examples [#real-world-examples] - **A game studio** ships a 4 GB patch to 300,000 players in an hour. With CloudFront in front of its download servers, the origin serves the file a few hundred times instead of 300,000. ## Exam tips [#exam-tips] - **"Decouple microservices, one shouldn't wait for another"** → SQS, SNS, Kinesis or EventBridge between them. - **"Microservices, pay only when used, little to manage"** → API Gateway + Lambda (or Fargate). - **"Large static downloads overload EC2, can't change the app"** → CloudFront in front of the existing origin. ## Common traps [#common-traps] - **"Scale the ASG further to serve the update."** It works but costs more; caching static files at the edge is the cheaper, simpler fix. - **"Microservices must all use the same stack."** Each service chooses what fits it. ## Check yourself [#check-yourself] Put an SQS queue between them: the order service sends a message and returns, and the billing service consumes the queue at its own pace (scaling on queue depth). Add a CloudFront distribution with the ALB as origin and long cache TTLs for the files. Downloads are served from edge caches, and the ASG stays small. ## AWS documentation [#aws-documentation] - [Implementing microservices on AWS](https://docs.aws.amazon.com/whitepapers/latest/microservices-on-aws/microservices-on-aws.html) - [Generate SDKs for REST APIs in API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-generate-sdk.html) - [Using various origins with CloudFront distributions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/DownloadDistS3AndCustomOrigins.html) # Serverless mobile app: MyTodoList (/docs/architecture/serverless-mobile-app) ## The app [#the-app] **MyTodoList** is a mobile to-do app. The requirements: - expose a **REST API over HTTPS**; - a **serverless** architecture; - users interact **directly with their own folder in S3**; - users sign in through a **managed serverless** service; - users write and read to-dos, but **mostly read** them; - the database must **scale** and give **high read throughput**.
![MyTodoList serverless mobile app: the app signs in with Amazon Cognito, which also gives it temporary AWS credentials to read and write its own folder in Amazon S3; it calls a REST API on API Gateway over HTTPS, which verifies the Cognito token, caches responses and invokes Lambda; Lambda queries DynamoDB through a DAX cache for microsecond reads](/diagrams/arch-mobile-app.light.svg) ![MyTodoList serverless mobile app: the app signs in with Amazon Cognito, which also gives it temporary AWS credentials to read and write its own folder in Amazon S3; it calls a REST API on API Gateway over HTTPS, which verifies the Cognito token, caches responses and invokes Lambda; Lambda queries DynamoDB through a DAX cache for microsecond reads](/diagrams/arch-mobile-app.dark.svg)
No servers to manage, from sign-in to database.
## The REST API layer [#the-rest-api-layer] - The app calls **[API Gateway](/docs/serverless/api-gateway)** over HTTPS. - API Gateway invokes **[Lambda](/docs/serverless/lambda)** functions that run the logic. - Lambda queries **[DynamoDB](/docs/databases/dynamodb)**, which scales without servers. - Users sign in with **[Amazon Cognito](/docs/identity/cognito)** user pools; API Gateway **verifies the token** on each call (a Cognito authorizer). ## Giving users access to S3 [#giving-users-access-to-s3] Users upload and download their files **straight to S3**, without going through the API: 1. The app signs the user in with Cognito. 2. A **[Cognito identity pool](/docs/identity/cognito#cognito-identity-pools)** exchanges the sign-in for **temporary AWS credentials** (through STS) tied to an IAM role. 3. The role's policy only allows the user's own prefix, with the policy variable `${cognito-identity.amazonaws.com:sub}`, for example `arn:aws:s3:::mytodolist-files/${cognito-identity.amazonaws.com:sub}/*`. The same pattern gives users direct, restricted access to **DynamoDB** (fine-grained access by partition key) or **Lambda**. ## High read throughput [#high-read-throughput] - **[DAX](/docs/databases/dynamodb-advanced#dynamodb-accelerator-dax)** sits in front of DynamoDB and caches reads in memory: **microsecond** reads, fewer read capacity units, and no code change beyond the DAX client. - **API Gateway caching** stores whole responses for a TTL (default 300 seconds, up to 3,600), so repeated requests never reach Lambda. It's a good fit for answers that change slowly and are the same for many users. ## What this lecture covered [#what-this-lecture-covered] - A serverless REST API: HTTPS, API Gateway, Lambda, DynamoDB. - Cognito generating **temporary credentials** to reach an S3 bucket with a restricted policy: app users access AWS resources directly. The pattern also works for DynamoDB and Lambda. - Caching reads on DynamoDB with **DAX**. - Caching REST requests at the **API Gateway** level. - Authentication and authorization with **Cognito**. ## Real-world examples [#real-world-examples] - **A note-taking app** with 2 million users stores attachments under `s3://notes-files//`, uploaded directly by the app with Cognito credentials; the API only stores metadata in DynamoDB. ## Exam tips [#exam-tips] - **"Mobile app users upload to their own folder in S3"** → Cognito **identity pool** + IAM policy with `${cognito-identity.amazonaws.com:sub}`. - **"Sign-in for a mobile or web app, serverless"** → Cognito **user pools**. - **"Read-heavy DynamoDB, microsecond latency"** → **DAX**. - **"Same responses requested again and again through API Gateway"** → **API Gateway caching**. ## Common traps [#common-traps] - **"Embed an IAM user's access keys in the mobile app."** Never: keys can be extracted. Use Cognito temporary credentials. - **"Proxy all file uploads through API Gateway and Lambda."** It works for small files but adds cost and limits (10 MB payloads on REST APIs); upload straight to S3. - **"DAX speeds up writes."** It caches reads; writes go through to DynamoDB. ## Check yourself [#check-yourself] Sign users in with Cognito, use an identity pool to give them temporary credentials for an IAM role, and restrict the role's S3 policy to the prefix `${cognito-identity.amazonaws.com:sub}/`. The app uploads directly to S3. Put DAX in front of the table so the hot items are served from memory, and turn on API Gateway caching for responses that don't change per user. ## AWS documentation [#aws-documentation] - [Control access to a REST API using Amazon Cognito user pools](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) - [IAM roles for Amazon Cognito identity pools](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html) - [Cache settings for REST APIs in API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-caching.html) - [In-memory acceleration with DynamoDB Accelerator (DAX)](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.html) # Serverless website: MyBlog.com (/docs/architecture/serverless-website) ## The app [#the-app] **MyBlog.com** must: - **scale globally**; - serve blogs that are **rarely written but often read**; - serve some of the site as **static files** and the rest through a **dynamic REST API**; - **cache** wherever possible; - send every new subscriber a **welcome email**; - generate a **thumbnail** for every photo uploaded to the blog. ## Static content and the API [#static-content-and-the-api]
![MyBlog.com serverless website: browsers get static files from CloudFront, which reads a private S3 bucket through Origin Access Control, with a bucket policy that allows only that distribution; dynamic requests go to a REST API on API Gateway, which invokes Lambda to query DynamoDB global tables through a DAX cache](/diagrams/arch-serverless-website.light.svg) ![MyBlog.com serverless website: browsers get static files from CloudFront, which reads a private S3 bucket through Origin Access Control, with a bucket policy that allows only that distribution; dynamic requests go to a REST API on API Gateway, which invokes Lambda to query DynamoDB global tables through a DAX cache](/diagrams/arch-serverless-website.dark.svg)
Static files from the edge, data from a global table.
- **Static content, globally:** **[CloudFront](/docs/edge/cloudfront)** in front of an **S3 bucket** caches the files in edge locations around the world. - **Securely:** the bucket stays **private**. CloudFront reads it with **[Origin Access Control](/docs/edge/cloudfront#s3-as-an-origin-with-oac)** (OAC), and the **bucket policy** only allows that CloudFront distribution. - **A public REST API:** API Gateway → Lambda → DAX → DynamoDB. The API is public, so it needs no Cognito. - **Globally:** **[DynamoDB global tables](/docs/databases/dynamodb-advanced#global-tables)** replicate the data to several Regions, so reads are local everywhere. (**Aurora Global Database** would also work for a relational model.) ## The welcome email flow [#the-welcome-email-flow]
![The welcome email flow: a new user item in the DynamoDB users table appears in the DynamoDB Stream, which invokes a Lambda function whose IAM role allows it to call Amazon SES, and SES sends the new user a welcome email](/diagrams/arch-blog-welcome.light.svg) ![The welcome email flow: a new user item in the DynamoDB users table appears in the DynamoDB Stream, which invokes a Lambda function whose IAM role allows it to call Amazon SES, and SES sends the new user a welcome email](/diagrams/arch-blog-welcome.dark.svg)
React to a new item, send an email.
- A new subscriber is a new item in the users table. - **[DynamoDB Streams](/docs/databases/dynamodb-advanced#stream-processing)** records the change and **invokes a Lambda** function. - The function's **IAM role** allows it to use **[Amazon SES](/docs/integration/ses-pinpoint#amazon-ses)**, which sends the email, with no mail server to run. ## The thumbnail flow [#the-thumbnail-flow]
![The thumbnail flow: the browser uploads a photo to an S3 bucket, through CloudFront for faster uploads; the S3 event invokes a Lambda function that writes a thumbnail to a second bucket, whose events can also go to SQS or SNS](/diagrams/arch-blog-thumbnail.light.svg) ![The thumbnail flow: the browser uploads a photo to an S3 bucket, through CloudFront for faster uploads; the S3 event invokes a Lambda function that writes a thumbnail to a second bucket, whose events can also go to SQS or SNS](/diagrams/arch-blog-thumbnail.dark.svg)
Every upload triggers its own thumbnail.
- Photos are uploaded to S3, directly or through CloudFront (or **S3 Transfer Acceleration**) for faster uploads from far away. - An **[S3 event notification](/docs/s3/event-notifications)** invokes Lambda, which resizes the image and writes the thumbnail to another bucket (writing back to the same prefix would trigger the function again). - The thumbnail bucket's own events can notify **SQS** or **SNS** (optional), for example to update a search index. ## Summary [#summary] - Static content is distributed with **CloudFront and S3**. - The REST API is **serverless**, and public, so it doesn't need Cognito. - A **global DynamoDB table** serves the data worldwide (Aurora Global Database is an alternative). - **DynamoDB Streams** triggers a Lambda function, whose IAM role lets it use **SES** to send emails serverlessly. - **S3** can trigger **SQS, SNS or Lambda** to react to events. ## Real-world examples [#real-world-examples] - **A recipe blog** serves its pages from CloudFront and S3 at a few dollars a month, and its search and comments API from Lambda and a DynamoDB global table in `us-east-1` and `eu-west-1`. ## Exam tips [#exam-tips] - **"Static website, global, secure, S3 not public"** → CloudFront + S3 with **OAC** and a bucket policy for the distribution. - **"Send an email when an item is added to DynamoDB"** → DynamoDB Streams → Lambda → SES. - **"Process images when they're uploaded"** → S3 event notification → Lambda. - **"Low-latency reads worldwide, NoSQL"** → DynamoDB global tables. ## Common traps [#common-traps] - **"Make the bucket public for CloudFront."** Use OAC and keep Block Public Access on. - **"Write thumbnails to the same bucket and prefix that triggers the function."** That creates an endless loop; use another bucket or a filtered prefix. ## Check yourself [#check-yourself] Create a CloudFront distribution with the bucket as origin and Origin Access Control, update the bucket policy to allow only that distribution, and turn on Block Public Access. Turn on DynamoDB Streams for the table, add a Lambda trigger that filters for new items, and give the function an IAM role that allows `ses:SendEmail`. ## AWS documentation [#aws-documentation] - [Restrict access to an Amazon S3 origin](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html) - [DynamoDB Streams and AWS Lambda triggers](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.Lambda.html) - [Tutorial: Using an Amazon S3 trigger to create thumbnail images](https://docs.aws.amazon.com/lambda/latest/dg/with-s3-tutorial.html) - [Global tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html) # Stateful web app: MyClothes.com (/docs/architecture/stateful-web-app) ## The app [#the-app] **MyClothes.com** is an online shop. Users browse, put clothes in a **shopping cart** and check out, and hundreds of them shop at the same time. The site must scale horizontally and keep the web tier as **stateless** as possible, but the cart and user details are **state**: they must not disappear when a request lands on a different server. It starts from the [stateless architecture](/docs/architecture/stateless-web-app): Route 53, an ALB across AZs and an Auto Scaling group. ## Where to keep the shopping cart [#where-to-keep-the-shopping-cart] 1. **Sticky sessions.** Turn on **[ELB stickiness](/docs/scaling/sticky-sessions-cross-zone)**: each user keeps going to the same instance, which holds their cart in memory. Simple, but if that instance is terminated, the cart is lost, and load can become uneven. 2. **Client-side cookies.** The browser sends the cart in a cookie with each request, so any instance can serve it: the web tier is **stateless**. But requests get heavier, cookies must stay **under 4 KB**, and users can tamper with them, so the server must **validate** them. 3. **Server-side sessions.** The cookie holds only a **session ID**. The instances store the session data in **[ElastiCache](/docs/databases/elasticache#user-session-store)** (sub-millisecond reads), or in **DynamoDB**. Any instance can read any session; this is the usual answer. ## Storing and reading data [#storing-and-reading-data] - **User data** (addresses, orders) goes in **[Amazon RDS](/docs/databases/rds)**: one primary takes the writes. - **Scaling reads:** most traffic is reading the catalog. Add up to 15 **[RDS read replicas](/docs/databases/rds-read-replicas-multi-az)** and send reads there. - **Or cache the reads** with **lazy loading** in ElastiCache: the app checks the cache first and queries RDS only on a miss, then stores the result. Less load on RDS, but you must think about cache invalidation. - **Surviving disasters:** the ALB is already Multi-AZ; turn on **RDS Multi-AZ** (standby in another AZ) and **ElastiCache Multi-AZ** (replicas with automatic failover).
![The final MyClothes.com: users reach an Application Load Balancer across AZs, which sends requests to EC2 instances in an Auto Scaling group in three AZs; the instances keep sessions and cached reads in ElastiCache, write to an RDS primary with Multi-AZ, and read from RDS read replicas fed by replication](/diagrams/arch-stateful-final.light.svg) ![The final MyClothes.com: users reach an Application Load Balancer across AZs, which sends requests to EC2 instances in an Auto Scaling group in three AZs; the instances keep sessions and cached reads in ElastiCache, write to an RDS primary with Multi-AZ, and read from RDS read replicas fed by replication](/diagrams/arch-stateful-final.dark.svg)
State moved out of the web tier.
## Security groups between tiers [#security-groups-between-tiers]
![Security groups for MyClothes.com: the ALB security group allows HTTPS 443 from anywhere; the EC2 security group allows traffic only from the ALB security group; the ElastiCache and RDS security groups allow traffic only from the EC2 security group](/diagrams/arch-stateful-sgs.light.svg) ![Security groups for MyClothes.com: the ALB security group allows HTTPS 443 from anywhere; the EC2 security group allows traffic only from the ALB security group; the ElastiCache and RDS security groups allow traffic only from the EC2 security group](/diagrams/arch-stateful-sgs.dark.svg)
Each tier only talks to the one in front of it.
- **ALB:** HTTP/HTTPS open to `0.0.0.0/0`. - **EC2:** inbound only from the **ALB's security group**. - **ElastiCache and RDS:** inbound only from the **EC2 security group**, on their ports (6379, 3306…). Referencing security groups instead of IP ranges keeps working as instances come and go. ## What this lecture covered [#what-this-lecture-covered] - **3-tier web apps**: web (ALB), application (EC2 in an ASG) and data (ElastiCache, RDS). - **ELB sticky sessions**, and **cookies** to make the web tier stateless. - **ElastiCache** for sessions (alternative: DynamoDB) and for caching RDS data, with Multi-AZ. - **RDS** for user data, **read replicas** for scaling reads, **Multi-AZ** for disaster recovery. - **Tight security** with security groups referencing each other. ## Real-world examples [#real-world-examples] - **A ticketing site** stores session IDs in cookies and sessions in ElastiCache with a 30-minute TTL, so a sale-day scale-out to 60 instances doesn't log anyone out. ## Exam tips [#exam-tips] - **"Users lose their session (cart, login) when instances scale in"** → store sessions in **ElastiCache** or **DynamoDB**, not on the instance. - **"Stateless web tier"** → session data outside the instances (cache, database, or signed cookies). - **"Read-heavy RDS"** → read replicas, or ElastiCache in front. - **"Database tier reachable only from the app tier"** → database security group allows the app tier's security group. ## Common traps [#common-traps] - **"Sticky sessions make the app highly available."** The session still dies with its instance. Use them only when you can't externalize the session. - **"Read replicas give high availability."** That's Multi-AZ. Replicas scale reads (though one can be promoted). - **"Store the whole cart in a cookie, it's stateless."** It works for small data, but cookies are limited to about 4 KB and must be validated. ## Check yourself [#check-yourself] Turn off the dependency on one instance: store session data in ElastiCache (or DynamoDB) keyed by a session ID in the user's cookie. Then stickiness isn't needed and scale-in doesn't lose carts. Add RDS read replicas and point the read queries at them, or add ElastiCache with lazy loading so repeated reads come from memory. ## AWS documentation [#aws-documentation] - [Sticky sessions for your Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html) - [Session management with ElastiCache](https://aws.amazon.com/caching/session-management/) - [Working with DB instance read replicas](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReadRepl.html) - [Security group rules for different use cases](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html) # Stateless web app: WhatIsTheTime.com (/docs/architecture/stateless-web-app) ## The app [#the-app] **WhatIsTheTime.com** tells people the time. It needs no database and keeps nothing about its users: every request can be answered by any server. That makes it **stateless**, the easiest kind of app to scale. We want to scale it **vertically and horizontally**, with **no downtime**, as traffic grows. The story goes in steps.
![WhatIsTheTime.com grows in four steps: one t2.micro instance with an Elastic IP; scale up to a bigger M5 instance with downtime; scale out to several instances with Route 53 A records, where a one-hour TTL leaves clients with stale IPs; then an Application Load Balancer with health checks and an Auto Scaling group across at least two Availability Zones](/diagrams/arch-stateless-steps.light.svg) ![WhatIsTheTime.com grows in four steps: one t2.micro instance with an Elastic IP; scale up to a bigger M5 instance with downtime; scale out to several instances with Route 53 A records, where a one-hour TTL leaves clients with stale IPs; then an Application Load Balancer with health checks and an Auto Scaling group across at least two Availability Zones](/diagrams/arch-stateless-steps.dark.svg)
Four steps from one server to a self-healing fleet.
## Step by step [#step-by-step] 1. **Start simple.** One `t2.micro` instance with a public IP. When it's restarted the public IP changes, so you attach an **[Elastic IP](/docs/compute/ip-addressing#elastic-ip-addresses)** to keep a fixed address. 2. **Scale vertically.** Traffic grows: stop the instance and change it to a bigger `m5.large`. It works, but the **stop causes downtime**, and one instance is still a single point of failure. 3. **Scale horizontally with Elastic IPs.** Add more instances, each with its own Elastic IP, and give users the list. Users must know every IP, and you're limited to 5 Elastic IPs per Region by default. 4. **Use Route 53 A records.** One name, `api.whatisthetime.com`, returns the IPs of all instances. But when you remove an instance, users who cached the answer keep using its old IP until the **TTL** (say 1 hour) expires. 5. **Add a load balancer.** Put the instances in **private** subnets behind a public **[Application Load Balancer](/docs/scaling/alb)** with **health checks**. The instances' security group allows traffic **only from the load balancer's security group**. Route 53 points to the ALB with an **[alias record](/docs/edge/route53-alias)** (the ALB's IPs change, so an A record with fixed IPs won't do). 6. **Add an Auto Scaling group.** An **[ASG](/docs/scaling/auto-scaling-groups)** adds and removes instances with demand and replaces unhealthy ones. 7. **Go Multi-AZ.** Spread the ALB and the ASG over **at least two AZs**, so losing a data center doesn't stop the app. 8. **Cut the cost.** You know the ASG always runs at least 2 instances: cover that **minimum** with **[Reserved Instances or Savings Plans](/docs/compute/purchasing-options)**, and let On-Demand (or Spot) handle the peaks. ## The final architecture [#the-final-architecture]
![The final WhatIsTheTime.com: users resolve the name with a Route 53 alias record, then send HTTPS requests to an Application Load Balancer with health checks, which spreads them across EC2 instances in an Auto Scaling group that spans Availability Zones A and B](/diagrams/arch-stateless-final.light.svg) ![The final WhatIsTheTime.com: users resolve the name with a Route 53 alias record, then send HTTPS requests to an Application Load Balancer with health checks, which spreads them across EC2 instances in an Auto Scaling group that spans Availability Zones A and B](/diagrams/arch-stateless-final.dark.svg)
The classic highly available web tier.
What the steps covered, in exam terms: - **public vs private IPs** and Elastic IPs on EC2; - **Route 53** A records, TTLs and alias records; - **ELB health checks** and **security groups that reference each other**; - **Auto Scaling groups** and **Multi-AZ** for high availability; - **reserved capacity** for the steady part of the load, to save cost. ## Real-world examples [#real-world-examples] - **A weather widget API** is served by 2–10 `t3.small` instances in an ASG across three AZs behind an ALB, with a Compute Savings Plan covering the 2 that always run. ## Exam tips [#exam-tips] - **"Highly available web tier on EC2"** → ALB + Auto Scaling group across at least two AZs. - **"Point a domain name at a load balancer"** → Route 53 **alias** record, never an A record with IPs. - **"Instances should only accept traffic from the load balancer"** → instance security group allows the ALB's security group as the source. - **"Steady minimum capacity, cheapest"** → Reserved Instances or Savings Plans for the minimum, On-Demand or Spot above it. ## Common traps [#common-traps] - **"Scaling vertically gives high availability."** It's still one instance, and resizing means downtime. - **"Use Route 53 A records with the instances' IPs to load balance."** Clients cache IPs for the TTL and keep hitting removed instances; there are no health-based replacements. Use an ELB. - **"Many Elastic IPs scale the app."** There's a quota of 5 per Region by default, and clients must know them all. ## Check yourself [#check-yourself] Create a launch template from the app's AMI, an Auto Scaling group over at least two AZs, and an Application Load Balancer with health checks in front. Point the domain at the ALB with a Route 53 alias record. Clients cached the old IP for the record's TTL. Put the instances behind a load balancer and use an alias record to it: the load balancer stops sending traffic to removed or unhealthy instances right away. ## AWS documentation [#aws-documentation] - [Elastic IP addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) - [Choosing between alias and non-alias records](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-choosing-alias-non-alias.html) - [Use Elastic Load Balancing to distribute traffic across the instances in your Auto Scaling group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html) # Well-Architected Framework and Trusted Advisor (/docs/architecture/well-architected) ## The Well-Architected Framework [#the-well-architected-framework] The **[AWS Well-Architected Framework](/docs/glossary#term-aws-well-architected-framework)** is AWS's set of best practices and questions for building secure, reliable, efficient, cost-effective and sustainable workloads. A review against it is meant as a **constructive conversation, not an audit**. ### General design principles [#general-design-principles] - **Stop guessing your capacity needs:** scale in and out automatically instead. - **Test systems at production scale:** create a full-size test environment on demand, then delete it. - **Automate with architectural experimentation in mind:** automation makes it cheap to try, track and revert changes. - **Consider evolutionary architectures:** design for changing requirements, not a fixed end state. - **Drive architectures using data:** measure how choices affect the workload, decide on facts. - **Improve through game days:** simulate events, such as a flash sale or an AZ outage, to see how the system and the team cope. ### The six pillars [#the-six-pillars]
![The six pillars of the AWS Well-Architected Framework: operational excellence, security, reliability, performance efficiency, cost optimization and sustainability](/diagrams/arch-wa-pillars.light.svg) ![The six pillars of the AWS Well-Architected Framework: operational excellence, security, reliability, performance efficiency, cost optimization and sustainability](/diagrams/arch-wa-pillars.dark.svg)
Six lenses on the same workload.
1. **Operational excellence:** run and monitor workloads, and keep improving processes. 2. **Security:** protect data, systems and assets. 3. **Reliability:** perform the intended function correctly and consistently, and recover from failures. 4. **Performance efficiency:** use resources efficiently, and keep doing so as demand and technology change. 5. **Cost optimization:** deliver business value at the lowest price point. 6. **Sustainability:** reduce energy use and waste, and get the most from the resources you provision. They're **not something to balance or trade off: they work together**. A well-automated system (operational excellence) is usually also more reliable and cheaper. The exam's four domains follow four of the pillars: secure, resilient (reliability), high-performing and cost-optimized architectures. The framework is updated regularly (last in November 2026). It now has a **Foundations** section on cloud foundations, alongside the pillars, and AWS publishes two custom lenses on GitHub, **Cloud Foundations** and **Cloud Workloads**, to review each with the Well-Architected Tool. The six pillars are unchanged. ## AWS Well-Architected Tool [#aws-well-architected-tool] The **[AWS Well-Architected Tool](/docs/glossary#term-aws-well-architected-tool)** is a **free** console service to **review your architectures** against the six pillars and **adopt best practices**. - **Define a workload** and **answer questions** about it, pillar by pillar. - It flags **high risk issues (HRIs)** and **medium risk issues (MRIs)** from your answers. - You get an **improvement plan** with videos and documentation, a **report**, and a **dashboard**; save **milestones** to track progress. - The **Well-Architected Framework Lens** is applied automatically; add official lenses from the **Lens Catalog** (serverless, SaaS, machine learning…) or your own **custom lenses** (up to 20 per workload). - Share workloads with other accounts, organizations or OUs. ## AWS Trusted Advisor [#aws-trusted-advisor] Trusted Advisor is in the course but not on the current SAA-C03 list of in-scope services. Know what it does; it's unlikely to be asked about in depth. **[AWS Trusted Advisor](/docs/glossary#term-aws-trusted-advisor)** gives a **high-level assessment of your AWS account**, with **nothing to install**. It analyzes your accounts and makes **recommendations** in six categories: - **cost optimization** (idle instances, unused Elastic IPs…); - **performance**; - **security** (public EBS or RDS snapshots, open security groups, MFA on the root user…); - **fault tolerance**; - **service limits** (quotas close to their limit); - **operational excellence**. Who gets what: - **Every account (Basic Support):** all **service limits** checks and a few core **security** and fault tolerance checks, refreshed by hand. - **Business Support+, Enterprise Support or Unified Operations:** the **full set of checks**, programmatic access with the **Trusted Advisor API**, and monitoring through **EventBridge**. The slides say "Business & Enterprise Support plan". AWS has reorganized its support plans: **Developer Support and Business Support end on 1 January 2027** (replaced by **Business Support+**, from $29 a month per account), and **Enterprise On-Ramp** customers move to Enterprise Support. The full set of Trusted Advisor checks now comes with **Business Support+, Enterprise Support or Unified Operations**. ## More architecture examples [#more-architecture-examples] You've now seen the most important patterns: - **classic:** EC2, ELB, RDS, ElastiCache…; - **serverless:** S3, Lambda, DynamoDB, CloudFront, API Gateway… For more, browse the [AWS Architecture Center](https://aws.amazon.com/architecture/) (reference architectures and diagrams) and the [AWS Solutions Library](https://aws.amazon.com/solutions/) (ready-to-deploy solutions such as [Instance Scheduler](/docs/cost/instance-scheduler)). The **Disaster Recovery of Workloads on AWS** whitepaper backs the [DR strategies](/docs/dr/dr-strategies) page. ## Real-world examples [#real-world-examples] - **A start-up** runs a Well-Architected review before launch: the tool flags an HRI for "no backups tested" and one for "root user without MFA", which become the first two items of its improvement plan. ## Exam tips [#exam-tips] - **"Review an architecture against AWS best practices"** → **Well-Architected Tool** (free). - **"Name the pillars"** → operational excellence, security, reliability, performance efficiency, cost optimization, sustainability. - **"Automatically check for idle resources, open security groups and service limits"** → **Trusted Advisor**. - **"Get notified when a service quota is close to its limit"** → Trusted Advisor service limits checks or **Service Quotas** CloudWatch alarms. ## Common traps [#common-traps] - **"The pillars are trade-offs: pick some."** AWS presents them as working together. - **"Trusted Advisor gives all checks to every account."** The full set needs Business Support+ or higher. ## AWS documentation [#aws-documentation] - [AWS Well-Architected Framework](https://docs.aws.amazon.com/wellarchitected/latest/framework/welcome.html) - [Framework design principles](https://docs.aws.amazon.com/wellarchitected/latest/framework/design-principles.html) - [Using lenses in the AWS Well-Architected Tool](https://docs.aws.amazon.com/wellarchitected/latest/userguide/lenses.html) - [AWS Trusted Advisor](https://docs.aws.amazon.com/awssupport/latest/user/trusted-advisor.html) - [AWS Trusted Advisor check reference](https://docs.aws.amazon.com/awssupport/latest/user/trusted-advisor-check-reference.html) # WordPress and fast launches: MyWordPress.com (/docs/architecture/wordpress) ## The app [#the-app] **MyWordPress.com** hosts a fully scalable WordPress website. - Users upload **pictures**, and every page must show them correctly. - **User data and blog content** live in a **MySQL** database. ## The database: Aurora [#the-database-aurora] The first version uses **RDS for MySQL with Multi-AZ**. Moving to **[Aurora MySQL](/docs/databases/aurora)** gives: - Multi-AZ storage (six copies across three AZs) and fast failover; - up to 15 **Aurora Replicas** behind a reader endpoint for reads; - less operations work, and **Aurora Global Database** if the site goes worldwide. ## Storing images: EBS or EFS [#storing-images-ebs-or-efs]
![Storing WordPress images: with Amazon EBS, the EC2 instance in AZ A and the one in AZ B each have their own EBS volume, so an image uploaded through one instance is missing on the other; with Amazon EFS, both instances reach one shared file system through an ENI mount target in their own AZ, so every instance sees every image](/diagrams/arch-wordpress-ebs-efs.light.svg) ![Storing WordPress images: with Amazon EBS, the EC2 instance in AZ A and the one in AZ B each have their own EBS volume, so an image uploaded through one instance is missing on the other; with Amazon EFS, both instances reach one shared file system through an ENI mount target in their own AZ, so every instance sees every image](/diagrams/arch-wordpress-ebs-efs.dark.svg)
Many instances need one shared file system.
- **One instance + [EBS](/docs/storage/ebs-volumes):** works fine. The image is saved on the instance's volume and served from it. - **Several instances + EBS:** an EBS volume belongs to one instance in one AZ. An image uploaded through instance A is saved on A's volume; a user served by instance B can't see it. - **Several instances + [EFS](/docs/storage/efs):** EFS is a network file system that many instances in many AZs mount at the same time, each through an **ENI (mount target)** in its AZ. Every instance sees every upload. In short: **EBS for a single-instance application, EFS for a distributed one.** (S3, with a WordPress plugin, is another common choice for media.) ## Instantiating applications quickly [#instantiating-applications-quickly] Launching a full stack (EC2, EBS, RDS) can take a long time: install software, load initial or recovery data, configure everything, start the app. The cloud lets you prepare in advance: - **EC2 instances:** - **[Golden AMI](/docs/compute/ami#golden-amis-and-fast-launches):** install the app, the OS updates and dependencies once, make an AMI, and launch every instance from it. - **Bootstrap with [user data](/docs/compute/ec2-basics#user-data-bootstrapping-an-instance):** for dynamic configuration at boot (fetch a config file, register the instance). - **Hybrid:** a golden AMI plus user data. **[Elastic Beanstalk](/docs/compute/elastic-beanstalk)** works this way. - **RDS databases:** restore from a **snapshot**: the schemas and data are already there. - **EBS volumes:** restore from a **snapshot**: the disk is already formatted and has the data. ## The typical 3-tier architecture [#the-typical-3-tier-architecture]
![A typical three-tier web app in a VPC: users reach an Application Load Balancer in the public subnet; it sends traffic to EC2 instances in an Auto Scaling group in the private subnet; the instances store sessions and cached data in ElastiCache and read and write data in RDS, both in a data subnet](/diagrams/arch-three-tier.light.svg) ![A typical three-tier web app in a VPC: users reach an Application Load Balancer in the public subnet; it sends traffic to EC2 instances in an Auto Scaling group in the private subnet; the instances store sessions and cached data in ElastiCache and read and write data in RDS, both in a data subnet](/diagrams/arch-three-tier.dark.svg)
Public, private and data subnets.
- **Public subnet:** the load balancer (and NAT gateways). - **Private subnet:** the application instances in an Auto Scaling group across AZs. - **Data subnet:** ElastiCache for sessions and cached data, RDS for reads and writes. Developers who'd rather not wire all this up themselves can let **Elastic Beanstalk** build it from their code. ## Real-world examples [#real-world-examples] - **A news site on WordPress** runs four instances in two AZs, with Aurora MySQL for posts and EFS for `wp-content/uploads`, behind an ALB and CloudFront. - **An HR company** bakes a golden AMI every Monday with the week's patches; new instances in its ASG start serving in under a minute instead of ten. ## Exam tips [#exam-tips] - **"Several EC2 instances must share files (uploads, content)"** → **EFS** (Linux) or **FSx for Windows File Server** (Windows). - **"MySQL, Multi-AZ, read scaling, less management"** → **Aurora MySQL**. - **"Instances take too long to boot because of software installs"** → **golden AMI**; use user data only for the dynamic part. - **"Database ready with data at launch"** → restore from an **RDS snapshot**. ## Common traps [#common-traps] - **"Attach the same EBS volume to all web servers."** EBS Multi-Attach is only for io1/io2, in one AZ, and needs a cluster-aware file system. Use EFS for shared web content. - **"User data makes launches fast."** Long installs in user data make launches slow; bake them into the AMI. ## Check yourself [#check-yourself] The images are on each instance's EBS volume. Move `wp-content/uploads` to an Amazon EFS file system mounted by every instance (mount targets in both AZs), or offload media to S3. Build a golden AMI with the packages already installed (for example with EC2 Image Builder), use it in the launch template, and keep only the small, dynamic configuration in user data. ## AWS documentation [#aws-documentation] - [Best practices for WordPress on AWS](https://docs.aws.amazon.com/whitepapers/latest/best-practices-wordpress/welcome.html) - [Amazon EFS: how it works](https://docs.aws.amazon.com/efs/latest/ug/how-it-works.html) - [Restoring to a DB instance from a snapshot](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_RestoreFromSnapshot.html) # AMIs (/docs/compute/ami) ## What it is [#what-it-is] An [Amazon Machine Image](/docs/glossary#term-ami) (AMI) is the **template** an instance is launched from. It contains the operating system, any software and configuration you added, and a list of the disks (EBS snapshots) to create. A custom AMI is a **customisation of an instance**: you add your software, settings and monitoring agents once, save the result as an AMI, and every instance launched from it starts with all of that already in place. Boot and setup are much faster than installing everything at launch. You can launch instances from: - **Public AMIs** provided by AWS, such as Amazon Linux 2023, or by OS vendors. Ones from Amazon or verified partners are marked *Verified provider*. - **Your own AMIs**, which you make and maintain. - **AWS Marketplace AMIs**, made (and often sold) by other companies, for example a pre-configured firewall or a licensed database. An AMI is specific to a **Region** (and to an OS, processor architecture and root volume type). To use it in another Region, you **copy** it there. ## Creating and using an AMI [#creating-and-using-an-ami]
![In us-east-1 an instance is set up, a custom AMI is created with EBS snapshots, and new instances launch from it; the AMI is copied to eu-west-1 with a new AMI ID to launch instances there](/diagrams/compute-ami-process.light.svg) ![In us-east-1 an instance is set up, a custom AMI is created with EBS snapshots, and new instances launch from it; the AMI is copied to eu-west-1 with a new AMI ID to launch instances there](/diagrams/compute-ami-process.dark.svg)
Create once, launch many times, copy to other Regions.
1. **Launch an instance and set it up**: install software, apply updates, configure it. 2. **Stop it** for data integrity. (If you don't, EC2 by default shuts it down and reboots it while creating the image, for the same reason. You can choose *no reboot* if you're sure the disk is consistent.) 3. **Create the AMI.** EC2 takes **EBS snapshots** of the instance's volumes; the AMI points to them. 4. **Launch new instances** from the AMI, in any AZ of the Region. 5. **Copy the AMI** to another Region if needed. The copy gets a new AMI ID, and you can encrypt it during the copy. You pay for the **snapshot storage** behind an AMI until you **deregister** the AMI and **delete** its snapshots. ## Sharing AMIs [#sharing-amis] - **With specific AWS accounts**, or with an **organization** or **OU** in AWS Organizations. - **Publicly**, with everyone (an account setting, *block public access for AMIs*, prevents this by default for new accounts). - **Encrypted AMIs** can be shared too, if the other account is also allowed to use the KMS key. - Sharing doesn't hand over ownership. The other account can copy the AMI to own its copy. ## Golden AMIs and fast launches [#golden-amis-and-fast-launches] A **[golden AMI](/docs/glossary#term-golden-ami)** is a company's approved, pre-built image with the OS, patches, security agents and the application already installed. Combined with other tricks, it gets a full stack running quickly: - **EC2 instances:** - a **golden AMI** for everything that's slow to install; - **user data** for the settings that change per launch (environment name, config URL); - a **hybrid** of both, which is what Elastic Beanstalk does. - **RDS databases:** restore from a **snapshot**, so the schema and data are already there. - **EBS volumes:** restore from a **snapshot**, so the disk is already formatted and filled. [EC2 Image Builder](/docs/glossary#term-ec2-image-builder) automates golden AMIs: it builds the image from a recipe on a schedule, tests it, and distributes it to other Regions and accounts. ## Exam tips [#exam-tips] - **"Launch instances faster", "pre-installed software", "reduce boot time"** → a golden AMI (plus user data for dynamic settings). - **"Use the same AMI in another Region"** → copy the AMI to that Region. - **"Share an AMI with another account"** → modify the AMI's permissions (and the KMS key policy if it's encrypted). - **"Automate building and patching AMIs"** → EC2 Image Builder. ## Common traps [#common-traps] - **"Launch an instance in eu-west-1 from an AMI ID in us-east-1."** AMIs are Regional; copy it first. - **"Deregistering the AMI stops the bill."** Its snapshots remain and keep costing until you delete them. - **"Configure everything in user data to save building AMIs."** Fine for small scripts, but slow for big installs; golden AMIs launch faster. ## Hands-on lab: build and use a custom AMI [#hands-on-lab-build-and-use-a-custom-ami] **Goal:** turn the web server into an AMI, launch a copy from it with no user data, and copy the AMI to another Region. Two `t3.micro` instances for a short time (about $0.02 an hour each), plus snapshot storage of about $0.05 per GB-month in each Region until you delete it. Together, a few cents. ### Create the AMI [#create-the-ami] Use `saa-web` from the [EC2 basics lab](/docs/compute/ec2-basics#hands-on-lab-launch-a-web-server-with-user-data) (launch it again if needed). Stop it, then choose **Actions → Image and templates → Create image**: name `saa-web-ami`, tag `Project=saa-lab`. Create. ### Wait for it [#wait-for-it] Open **Images → AMIs**. When the status is *Available*, open **Elastic Block Store → Snapshots**: a new snapshot was created for the AMI. ### Launch from your AMI [#launch-from-your-ami] Select `saa-web-ami` and choose **Launch instance from AMI**: name `saa-from-ami`, `t3.micro`, key pair `saa-lab-key`, security group `saa-web-sg`, **no user data**. Launch, then open its public IP in the browser. The web page works straight away: the web server was already in the image. ### Copy to another Region [#copy-to-another-region] Select the AMI, **Actions → Copy AMI**, destination Region **US West (Oregon)**. Switch the console to us-west-2: the copy appears under **AMIs** with a different AMI ID. **Expected result:** an instance that serves the web page without any setup, and the same image available in a second Region. **Clean up:** terminate `saa-from-ami` and `saa-web`. In **each** Region, **deregister** the AMI, then delete its snapshot under **Snapshots**. ## AWS documentation [#aws-documentation] - [Amazon Machine Images in Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) - [Create an Amazon EBS-backed AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html) - [Copy an Amazon EC2 AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/CopyingAMIs.html) - [Understand shared AMI usage in Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharing-amis.html) - [What is EC2 Image Builder?](https://docs.aws.amazon.com/imagebuilder/latest/userguide/what-is-image-builder.html) # AWS Batch (/docs/compute/batch) ## What it is [#what-it-is] A **batch job** has a start and an end: render a video, process yesterday's sales files, run a genome analysis. That's the opposite of a web server, which runs continuously. Companies often have thousands of such jobs, and running them means managing a scheduler, a queue and a fleet of servers. [AWS Batch](/docs/glossary#term-aws-batch) does that for you: **fully managed batch processing at any scale**, up to hundreds of thousands of jobs. - You **submit or schedule** jobs; Batch does the rest. - Batch **launches EC2 instances or Spot Instances** (or uses Fargate) dynamically, sized to the jobs waiting, and removes them when the queue is empty. - Jobs are defined as **Docker images** and run on Amazon **ECS** or **EKS**. - There's **no extra charge** for Batch: you pay only for the EC2, Spot or Fargate capacity the jobs use. With Spot, that's a big saving. ## How it works [#how-it-works] - **Job definition:** a template for a job: the container image, vCPUs, memory, command, IAM role, retry policy. - **Job queue:** where submitted jobs wait. Queues have priorities. - **Compute environment:** the capacity that runs the jobs: **managed** (Batch picks and scales the instances, On-Demand or Spot, or uses Fargate) or **unmanaged** (you run the instances). - **Scheduler:** decides which job runs next, and where. Batch can also run *array jobs* (the same job thousands of times on different inputs) and *multi-node parallel jobs* that span several instances for tightly coupled HPC work. ### A simple example [#a-simple-example]
![A file uploaded to S3 triggers an EventBridge rule that submits a job; AWS Batch runs it on EC2, Spot or Fargate and saves the result to S3](/diagrams/compute-batch-flow.light.svg) ![A file uploaded to S3 triggers an EventBridge rule that submits a job; AWS Batch runs it on EC2, Spot or Fargate and saves the result to S3](/diagrams/compute-batch-flow.dark.svg)
An event-driven image-processing pipeline.
1. A user uploads an image to an **S3** bucket. 2. An **EventBridge rule** reacts to the upload and **submits a Batch job** (Batch jobs can also run on a schedule). 3. **AWS Batch** puts the job in its queue and starts capacity in the compute environment: On-Demand, **Spot**, or Fargate. 4. The job's container processes the image and **writes the result** to another S3 bucket. When the queue is empty, the capacity scales back to zero. ## Batch vs Lambda [#batch-vs-lambda] Both run code without you managing servers, but they suit different jobs: - **AWS Lambda** - **time limit** per invocation; - a limited set of **runtimes** (or a container image built for Lambda); - limited **temporary disk** space (`/tmp`); - **serverless**: nothing to scale or patch, billed per millisecond. - **AWS Batch** - **no time limit**: jobs can run for hours or days; - **any runtime**, as long as it's packaged as a Docker image; - disk space from **EBS or instance store**, so jobs can use large local storage; - runs on **EC2** (managed by AWS) or Fargate, and can use GPUs. Rule of thumb: short, event-driven tasks → Lambda. Long, heavy or GPU jobs → Batch. Lambda's maximum timeout is now **30 minutes** (it was 15 minutes for years, and many practice questions still say 15). Memory and `/tmp` both go up to 10,240 MB. Batch can also now use **ECS Managed Instances** as capacity and queue **SageMaker training jobs**. ## Real-world examples [#real-world-examples] - **A pharmaceutical company** screens millions of molecules with array jobs on Spot Instances overnight. - **A media company** transcodes every uploaded video with a Batch job that runs for 40 minutes on a GPU instance, too long for Lambda. - **A bank** runs end-of-day risk calculations as a queue of jobs with priorities. ## Exam tips [#exam-tips] - **"Run batch jobs at scale", "hundreds of thousands of jobs", "managed job scheduling"** → AWS Batch. - **"Job runs longer than Lambda allows", "needs a custom runtime or GPU", "needs lots of disk"** → Batch, not Lambda. - **"Reduce the cost of batch processing"** → Batch with **Spot** compute environments. - **Batch jobs are Docker images**, running on ECS/EKS with EC2, Spot or Fargate capacity. ## Common traps [#common-traps] - **"Batch is a serverless function service."** It runs containers on EC2 or Fargate capacity, which you pay for. - **"Use Lambda for a 3-hour job."** Lambda's timeout is far shorter. ## Hands-on lab: run a job on Fargate [#hands-on-lab-run-a-job-on-fargate] **Goal:** create a Fargate compute environment, a job queue and a job definition, and run a container job. Fargate bills per second for the job's vCPU and memory. A job of 1 vCPU and 2 GB that runs for a minute costs well under a cent. Batch itself is free. ### Start the wizard [#start-the-wizard] Open **AWS Batch** in us-east-1 and choose **Wizard** (or **Get started**). Orchestration type **Fargate**. ### Compute environment and queue [#compute-environment-and-queue] Name the compute environment `saa-batch-ce`, maximum vCPUs **4**, the default VPC and its subnets. Name the job queue `saa-batch-queue`. ### Job definition [#job-definition] Name `saa-hello`, image `public.ecr.aws/amazonlinux/amazonlinux:latest`, command `echo Hello from AWS Batch`, 1 vCPU, 2 GB memory. Turn **Assign public IP** on, so the job can pull the image from the internet. Let the wizard create the execution role. ### Submit and watch [#submit-and-watch] Submit a job named `hello-1` to `saa-batch-queue`. In **Jobs**, watch it go *Submitted → Runnable → Starting → Running → Succeeded*. Open the job and follow the **log stream** link: CloudWatch Logs shows *Hello from AWS Batch*. **Expected result:** a container job that ran on capacity Batch started for it and then released. **Clean up:** disable and delete the job queue, then disable and delete the compute environment, and deregister the job definition. Delete the CloudWatch log group `/aws/batch/job` if you like (log storage is tiny). ## AWS documentation [#aws-documentation] - [What is AWS Batch?](https://docs.aws.amazon.com/batch/latest/userguide/what-is-batch.html) - [Components of AWS Batch](https://docs.aws.amazon.com/batch/latest/userguide/batch_components.html) - [Lambda quotas](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html) # AWS Compute Optimizer (/docs/compute/compute-optimizer) AWS Compute Optimizer is on the exam's in-scope list, but the slides don't cover it. This page is written from the AWS documentation. ## What it is [#what-it-is] People usually pick instance sizes once, at launch, and guess generously. A year later many servers are far bigger than they need to be, and a few are too small and slow. Finding them by hand means reading weeks of graphs for every resource. [AWS Compute Optimizer](/docs/glossary#term-aws-compute-optimizer) does that analysis for you. It looks at the **configuration** and the **utilisation metrics** of your resources and gives **right-sizing recommendations** that lower costs, improve performance, or both. It also finds **idle** resources you can stop or delete. - **Free.** Only the optional *enhanced infrastructure metrics* feature is paid. - **Opt in first:** it analyses nothing until you opt in, for one account or for a whole AWS organization from the management account. ## How it works [#how-it-works]
![Compute Optimizer reads 14 days of CloudWatch metrics and labels resources over-provisioned, under-provisioned or idle](/diagrams/compute-optimizer-flow.light.svg) ![Compute Optimizer reads 14 days of CloudWatch metrics and labels resources over-provisioned, under-provisioned or idle](/diagrams/compute-optimizer-flow.dark.svg)
From metrics to findings.
1. After you opt in, Compute Optimizer reads each resource's specifications and its **CloudWatch metrics from the last 14 days**: CPU use, network, disk reads and writes, and more. 2. It uses **machine learning** to compare that usage with what other instance types and sizes would give. 3. Each resource gets a **finding**: - **Over-provisioned:** bigger than needed. Downsize to save money. - **Under-provisioned:** too small for the workload. Upsize for performance. - **Optimized:** about right. - **Idle:** barely used. Stop or delete it. 4. For each resource it shows up to three recommended options, with the expected price and performance risk, and graphs of what the utilisation would look like. A resource needs enough data before it gets a recommendation: for example **at least 30 hours** of metrics for an EC2 instance. ### What it covers [#what-it-covers] EC2 instances, **EC2 Auto Scaling groups**, **EBS volumes**, **Lambda functions** (memory size), **ECS services on Fargate**, **RDS and Aurora** databases, commercial software licences, and more, including NAT gateways and some other database services. ### Better recommendations [#better-recommendations] - **Memory metrics:** CPU is collected by default, but memory isn't. Installing the **CloudWatch agent** (or sending memory metrics from tools such as Datadog) gives much better EC2 advice. - **Enhanced infrastructure metrics** (paid, about $0.0003 per resource per hour): looks back **93 days** instead of 14, to catch monthly or quarterly peaks. - **Preferences:** you can tell it how much headroom to leave, or which instance families to prefer, such as Graviton. ## Where it fits [#where-it-fits] - **Compute Optimizer:** is each resource the right size? - **[Cost Explorer](/docs/cost/cost-explorer-anomaly) and [AWS Budgets](/docs/cost/budgets-cur-tags#aws-budgets)** (Cost Management group): how much are we spending, and on what? - **Savings Plans and RIs**: how do we pay less for what we keep running? Right-size first, then commit: buying a Savings Plan for oversized servers locks in the waste. ## Exam tips [#exam-tips] - **"Recommend optimal instance types / sizes based on utilisation"**, **"right-sizing"**, **"identify over-provisioned EC2 instances"** → AWS Compute Optimizer. - **"Recommend Lambda memory size"** or **"EBS volume type"** → Compute Optimizer too. - **"Include memory utilisation in recommendations"** → install the CloudWatch agent. ## Common traps [#common-traps] - **"Compute Optimizer changes the instances for you."** It only recommends; you apply the changes. - **"Recommendations appear the moment you opt in."** It needs about a day to analyse, and enough metric history per resource. ## Hands-on lab: opt in and check back [#hands-on-lab-opt-in-and-check-back] **Goal:** turn on Compute Optimizer and read its findings once your resources have enough history. Opting in and the standard recommendations are free. Don't turn on *enhanced infrastructure metrics*, which is paid. ### Opt in [#opt-in] Open **AWS Compute Optimizer** in the console and choose **Get started**. Choose **Only this account** (or all accounts if you're in the management account of your lab organization) and **Opt in**. ### Look at the dashboard [#look-at-the-dashboard] The dashboard is empty at first and says data is being analysed. If you have an instance that has been running for more than 30 hours, check back the next day. ### Read a recommendation [#read-a-recommendation] When findings appear, open **EC2 instances**, choose an instance and read its finding, the three recommended options, and the utilisation graphs. A small lab instance usually shows *Optimized* or *Over-provisioned*. **Expected result:** Compute Optimizer is active for your account and starts producing findings once resources have enough metrics. **Clean up:** nothing costs money. You can opt out again in the Compute Optimizer account settings if you prefer. ## AWS documentation [#aws-documentation] - [What is AWS Compute Optimizer?](https://docs.aws.amazon.com/compute-optimizer/latest/ug/what-is-compute-optimizer.html) - [Resource requirements](https://docs.aws.amazon.com/compute-optimizer/latest/ug/requirements.html) - [Viewing EC2 instance recommendations](https://docs.aws.amazon.com/compute-optimizer/latest/ug/view-ec2-recommendations.html) - [Enhanced infrastructure metrics](https://docs.aws.amazon.com/compute-optimizer/latest/ug/enhanced-infrastructure-metrics.html) - [AWS Compute Optimizer pricing](https://aws.amazon.com/compute-optimizer/pricing/) # Connecting to EC2 (/docs/compute/connecting-to-ec2) ## What it is [#what-it-is] To run commands on a Linux instance you open a **remote shell** on it. The classic way is **SSH** (Secure Shell) on port 22 with a key pair. AWS also offers ways that need no key file, and even ways that need no open port or public IP. For Windows instances you use **RDP** (Remote Desktop) on port 3389 instead. ## The four ways to connect to Linux [#the-four-ways-to-connect-to-linux]
![Four ways to connect: SSH or PuTTY over the internet, EC2 Instance Connect from the browser, Session Manager through the SSM Agent, and an EIC Endpoint to a private IP](/diagrams/compute-connect-options.light.svg) ![Four ways to connect: SSH or PuTTY over the internet, EC2 Instance Connect from the browser, Session Manager through the SSM Agent, and an EIC Endpoint to a private IP](/diagrams/compute-connect-options.dark.svg)
What each method needs on the instance side.
### SSH client or PuTTY [#ssh-client-or-putty] You connect from your own computer to the instance's **public IP** on **port 22**, proving who you are with the private key of the instance's [key pair](/docs/glossary#term-key-pair). - **macOS, Linux and Windows 10 or later** have the `ssh` command built in. - **Older Windows** uses the free **PuTTY** tool, which needs the key in `.ppk` format (PuTTYgen converts a `.pem`). - The security group must allow port 22 from your IP, and the instance needs a public IP. ```bash chmod 400 saa-lab-key.pem ssh -i saa-lab-key.pem ec2-user@ ``` The username depends on the AMI: `ec2-user` for Amazon Linux, `ubuntu` for Ubuntu. ### EC2 Instance Connect [#ec2-instance-connect] [EC2 Instance Connect](/docs/glossary#term-ec2-instance-connect) opens an SSH session **in your browser** from the EC2 console, or from your own SSH client with the AWS CLI. - You don't need your key file. AWS **pushes a temporary public key** to the instance, valid for **60 seconds**, and connects with it. - **IAM policies** decide who may connect, and every connection is logged in CloudTrail. - It's pre-installed on **Amazon Linux 2023, Amazon Linux 2 and Ubuntu 20.04 or later**. - The instance still needs a **public IP** and **port 22** open, from the EC2 Instance Connect service's IP range (an AWS-managed prefix list) when you use the console. - No extra charge. ### Session Manager [#session-manager] [Session Manager](/docs/glossary#term-session-manager), part of AWS Systems Manager, opens a shell through the **SSM Agent** running on the instance. - **No inbound port, no SSH keys, no public IP needed.** The agent connects out to Systems Manager, so the security group can have zero inbound rules. - The instance needs an **IAM role** with the `AmazonSSMManagedInstanceCore` policy, and a route to the Systems Manager endpoints (internet access or VPC endpoints). - Access is controlled with IAM, and sessions can be logged to S3 or CloudWatch Logs. - Works for Linux and Windows. The agent is pre-installed on Amazon Linux and recent Windows AMIs. It's the most secure option and the one AWS recommends for admin access. It's covered again in the Monitoring & Governance group. ### EC2 Instance Connect Endpoint [#ec2-instance-connect-endpoint] An **EC2 Instance Connect Endpoint** (EIC Endpoint) lets you reach instances that have **only a private IP**, from the internet, without a bastion host or internet gateway. - You create the endpoint in a subnet of your VPC. It acts as an identity-aware proxy: IAM checks you before any traffic enters the VPC. - It supports SSH and RDP. The instance's security group allows port 22 (or 3389) from the endpoint. - No extra charge, apart from data transfer between AZs. The slides say EC2 Instance Connect works out of the box only with Amazon Linux 2. It now also comes pre-installed on Amazon Linux 2023 and Ubuntu 20.04 and later. The EC2 Instance Connect Endpoint (2023) isn't in the slides; it's how AWS now suggests reaching private instances without a bastion host. ## Troubleshooting SSH [#troubleshooting-ssh] Most connection problems are one of these: - **Connection times out:** the security group doesn't allow port 22 from your current IP (your home IP may have changed), or the instance has no public IP or isn't in a public subnet. - **Permission denied (publickey):** wrong key file, wrong username, or the key file permissions are too open (run `chmod 400` on it). - **Unprotected private key file:** same fix, `chmod 400`. - **Connection refused:** the instance is still booting, or the SSH service isn't running. - **Nothing works:** use EC2 Instance Connect or Session Manager instead. Any one working method is enough. ## Exam tips [#exam-tips] - **"Connect without opening port 22"**, **"no SSH keys"**, **"no bastion host"**, **"audit sessions"** → Session Manager. - **"Connect to an instance with no public IP from the internet, without a bastion"** → EC2 Instance Connect Endpoint (or Session Manager). - **"Temporary SSH key, controlled by IAM"** → EC2 Instance Connect. - **Port 22** for SSH to Linux, **port 3389** for RDP to Windows. ## Common traps [#common-traps] - **"EC2 Instance Connect needs no open port."** It still uses SSH on port 22. Session Manager is the one with no inbound port. - **"Lost the key pair? Download it again."** AWS keeps only the public key. Use Instance Connect or Session Manager to get in, or attach the volume to another instance. - **"Allow SSH from 0.0.0.0/0."** Works, but exposes the instance to the whole internet. Restrict it to your IP. ## Hands-on lab: three ways in [#hands-on-lab-three-ways-in] **Goal:** connect to the same instance with SSH, EC2 Instance Connect and Session Manager. Uses the `saa-web` instance, about **$0.02 an hour**. Session Manager itself has no charge for shell sessions. ### SSH from your computer [#ssh-from-your-computer] On macOS or Linux, or Windows 10 and later in PowerShell, go to the folder with `saa-lab-key.pem` and run: ```bash chmod 400 saa-lab-key.pem ssh -i saa-lab-key.pem ec2-user@ ``` Type `yes` at the fingerprint question. You're in: try `whoami` and `curl localhost`. Type `exit` to leave. (On Windows, `chmod` isn't needed; use PuTTY with a `.ppk` key on older versions.) ### EC2 Instance Connect [#ec2-instance-connect-1] In the console, select `saa-web` and choose **Connect → EC2 Instance Connect → Connect**. A shell opens in a browser tab, with no key file. If it fails, add an inbound rule to `saa-web-sg` for port 22 from the prefix list `com.amazonaws.us-east-1.ec2-instance-connect`. ### Give the instance a role for Session Manager [#give-the-instance-a-role-for-session-manager] Open **IAM → Roles → Create role**, trusted entity **AWS service → EC2**, attach `AmazonSSMManagedInstanceCore`, name it `saa-ssm-role`. Then in EC2 select `saa-web` and choose **Actions → Security → Modify IAM role**, pick `saa-ssm-role` and save. ### Connect with Session Manager [#connect-with-session-manager] Wait a minute or two, then choose **Connect → Session Manager → Connect**. You get a shell as `ssm-user`. Now remove the SSH rule from `saa-web-sg` and connect with Session Manager again: it still works, because no inbound port is needed. **Expected result:** three working shells, and proof that Session Manager needs no inbound rule. **Clean up:** terminate `saa-web` if you're not continuing to the [IP addressing lab](/docs/compute/ip-addressing). Detaching the role isn't needed, but you can delete `saa-ssm-role` when you finish this group. ## AWS documentation [#aws-documentation] - [Connect to your EC2 instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect.html) - [Connect to your Linux instance using EC2 Instance Connect](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-linux-inst-eic.html) - [Connect using EC2 Instance Connect Endpoint](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-with-ec2-instance-connect-endpoint.html) - [AWS Systems Manager Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html) - [Troubleshoot issues connecting to your Amazon EC2 Linux instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) # EC2 basics (/docs/compute/ec2-basics) ## What it is [#what-it-is] [Amazon EC2](/docs/glossary#term-amazon-ec2) (Elastic Compute Cloud) rents you **virtual servers**, called *instances*, in the AWS Cloud. It's AWS's main [Infrastructure as a Service](/docs/glossary#term-iaas) offering: AWS runs the physical hardware and the virtualisation layer, and you get a machine you can log in to, install software on and run as you like. EC2 exists because buying servers is slow and risky. A physical server takes weeks to arrive and you pay for it whether it's busy or not. An EC2 instance starts in about a minute, is billed by the second, and can be thrown away when you're done. EC2 is also the base of a whole family of features that later groups cover: - **Virtual disks** with [Amazon EBS](/docs/storage/ebs-volumes). - **Spreading traffic** across instances with [Elastic Load Balancing](/docs/scaling/elb-overview). - **Adding and removing instances** automatically with [Auto Scaling groups](/docs/scaling/auto-scaling-groups). ## What you choose when you launch an instance [#what-you-choose-when-you-launch-an-instance]
![The choices around an EC2 instance: AMI, instance type, user data, storage, security group and key pair](/diagrams/compute-ec2-anatomy.light.svg) ![The choices around an EC2 instance: AMI, instance type, user data, storage, security group and key pair](/diagrams/compute-ec2-anatomy.dark.svg)
The main launch choices.
- **[AMI](/docs/glossary#term-ami)** (Amazon Machine Image): the template with the operating system and any pre-installed software. Linux, Windows and macOS are available. See [AMIs](/docs/compute/ami). - **[Instance type](/docs/glossary#term-instance-type)**: how much CPU (vCPUs), memory and network performance you get, for example `t3.micro` or `m7g.2xlarge`. See [Instance types](/docs/compute/instance-types). - **Storage**: network-attached volumes ([EBS](/docs/storage/ebs-volumes), [EFS](/docs/storage/efs)) or the server's own local disks ([instance store](/docs/storage/instance-store)). - **Network settings**: which VPC and subnet the instance goes in, and whether it gets a public IP address. See [IP addressing](/docs/compute/ip-addressing). - **[Security group](/docs/glossary#term-security-group)**: the firewall rules for the instance. See [Security groups](/docs/compute/security-groups). - **[Key pair](/docs/glossary#term-key-pair)**: the SSH key used to log in to Linux instances (or to decrypt the Windows Administrator password). See [Connecting to EC2](/docs/compute/connecting-to-ec2). - **[User data](/docs/glossary#term-user-data)**: an optional script that runs when the instance first starts. An [IAM role](/docs/identity/roles-and-sts) can also be attached, so code on the instance can call AWS services without access keys. ## User data: bootstrapping an instance [#user-data-bootstrapping-an-instance] *Bootstrapping* means running commands automatically when a machine starts, so it comes up ready to work. On EC2 you do this with a **user data** script. - By default it runs **only once**, at the instance's **first** start. - It runs as the **root** user, so it can install packages and change system settings without `sudo`. - It's limited to **16 KB**. - Typical jobs: install updates and software, download files, write configuration, start a service. This script turns a fresh Amazon Linux 2023 instance into a small web server: ```bash #!/bin/bash dnf install -y httpd echo "

Hello from $(hostname -f)

" > /var/www/html/index.html systemctl enable --now httpd ``` User data is good for settings that change per launch. For software that takes a long time to install, a pre-built [golden AMI](/docs/compute/ami#golden-amis-and-fast-launches) starts faster. Many teams combine the two. ## The instance life cycle [#the-instance-life-cycle] What you're billed for depends on the instance's state: - **Pending → running:** the instance boots. While it's running you pay for it **per second**, with a **60-second minimum** each time it starts (Linux, Windows and most other systems; a few commercial OS images bill per hour). - **Stop:** the instance shuts down. You don't pay for the instance while it's stopped, but you still pay for its EBS volumes. Its public IP address is released. Starting it again usually moves it to new hardware. - **Reboot:** like restarting your PC. It stays on the same host, keeps its IP addresses, and doesn't start a new 60-second minimum. - **Terminate:** the instance is deleted. By default its root EBS volume is deleted too (the [Delete on termination](/docs/storage/ebs-volumes#delete-on-termination) setting). This can't be undone. - **Hibernate:** a stop that also saves the memory contents. See [EC2 Hibernate](/docs/compute/hibernate). ## Pricing [#pricing] An instance's bill has several parts: - **The instance**, by the second, at the rate for its type, Region and OS. A `t3.micro` running Linux in us-east-1 costs about $0.0104 an hour. - **EBS storage**, per GB-month, even while the instance is stopped. - **Public IPv4 addresses**, $0.005 an hour each, whether the instance uses them or not. - **Data transfer** out to the internet and between AZs or Regions. How you buy the instance can cut the first part by up to 90%. See [Purchasing options](/docs/compute/purchasing-options). The course launches `t2.micro` instances under the old 12-month free tier. AWS changed the free tier for accounts created from July 2025: new accounts get credits for 6 months, usable on types such as `t3.micro` and `t4g.micro`. `t2` is a previous-generation family, so these notes use `t3.micro`. AWS has also charged for every public IPv4 address since February 2024. ## Real-world examples [#real-world-examples] - **A small business website** runs on one `t3.small` instance with a user data script that installs WordPress. - **A game studio** launches 200 instances for a weekend tournament and terminates them on Monday, paying only for those hours. - **A bank** runs a vendor's risk engine on EC2 because the vendor only supports one specific Linux version. ## Exam tips [#exam-tips] - **"Bootstrap instances at launch"**, **"install software when the instance starts"** → user data. - **User data runs once, as root**, at first boot by default. - **"Pay only while running"** → stop instances you don't need; storage is still billed. - **Terminating deletes the root EBS volume by default** (the *DeleteOnTermination* setting); extra volumes are kept by default. ## Common traps [#common-traps] - **"Put the database password in the user data."** User data isn't encrypted and can be read from inside the instance and by anyone allowed to view it. Use Secrets Manager or Parameter Store. - **"User data runs on every reboot."** Only on the first start, unless you configure it otherwise. - **"A stopped instance costs nothing."** Its EBS volumes and any Elastic IPs are still billed. ## Hands-on lab: launch a web server with user data [#hands-on-lab-launch-a-web-server-with-user-data] **Goal:** launch a Linux instance that installs and starts a web server by itself, then see what stop and start do to it. A `t3.micro` instance, its public IPv4 address and an 8 GB gp3 volume cost about **$0.02 an hour** together. Terminate the instance when you finish (or after the next labs, which reuse it). ### Start the launch wizard [#start-the-launch-wizard] Open the **EC2 console** in **us-east-1** and choose **Launch instances**. Name the instance `saa-web`, then choose **Add additional tags** and add `Project` = `saa-lab`. ### Choose the AMI and type [#choose-the-ami-and-type] Keep **Amazon Linux 2023** (the default AMI). For **Instance type**, choose `t3.micro`. ### Create a key pair [#create-a-key-pair] Under **Key pair**, choose **Create new key pair**: name `saa-lab-key`, type RSA, format `.pem` (or `.ppk` if you'll use PuTTY). Your browser downloads it. Keep it: the next labs use it. ### Network and firewall [#network-and-firewall] Under **Network settings**, keep the default VPC and **Auto-assign public IP: Enable**. Choose **Create security group**, name it `saa-web-sg`, tick **Allow SSH traffic from: My IP**, and tick **Allow HTTP traffic from the internet**. ### Add the user data [#add-the-user-data] Keep the default 8 GiB gp3 storage. Open **Advanced details**, scroll to **User data**, and paste the web server script from the [user data section](#user-data-bootstrapping-an-instance) above. Choose **Launch instance**. ### Open the website [#open-the-website] In **Instances**, wait until the state is *Running* and the status checks show *2/2 checks passed*. Copy the **Public IPv4 address** and open `http://` followed by it in your browser (use `http`, not `https`). You'll see *Hello from ip-172-31-…*. ### Stop and start [#stop-and-start] Select the instance, choose **Instance state → Stop**, and watch the public IP disappear. Then **Start** it. It gets a **new** public IP. Open the new address: the page still works, because `systemctl enable` made the web server start on every boot, even though the user data didn't run again. **Expected result:** a web page served from your instance without logging in to it, and proof that stopping releases the public IP while the instance and its disk survive. **Clean up:** if you're doing the [Security groups](/docs/compute/security-groups) and [Connecting to EC2](/docs/compute/connecting-to-ec2) labs today, keep `saa-web`. Otherwise choose **Instance state → Terminate (delete) instance**. Keep the key pair file; key pairs are free.
Beyond the exam: instance metadata Every instance can query information about itself at `http://169.254.169.254/latest/meta-data/`: its instance ID, AMI, IP addresses, IAM role credentials and its user data. This is the *instance metadata service* (IMDS). Version 2 (**IMDSv2**) requires a session token first, which blocks a class of attacks where a web app is tricked into fetching that URL for an attacker: ```bash TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id ``` New instances launched from current AMIs require IMDSv2 by default. You can enforce it account-wide.
## AWS documentation [#aws-documentation] - [What is Amazon EC2?](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) - [Run commands when you launch an EC2 instance with user data input](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) - [Amazon EC2 instance state changes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) - [Use the Instance Metadata Service to access instance metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html) - [Amazon EC2 On-Demand pricing](https://aws.amazon.com/ec2/pricing/on-demand/) # Elastic Beanstalk (/docs/compute/elastic-beanstalk) ## What it is [#what-it-is] Most web apps on AWS end up with the same building blocks: EC2 instances in an Auto Scaling group behind a load balancer, often with an RDS database, spread across AZs. Building, configuring and updating that by hand takes time, and developers mostly just want their code to run, the same way in every environment. [AWS Elastic Beanstalk](/docs/glossary#term-aws-elastic-beanstalk) is a **developer-centric** way to deploy an app on AWS. You upload your code; Beanstalk creates and manages the EC2 instances, Auto Scaling group, load balancer, health monitoring and configuration. - It's a **managed service**: capacity provisioning, load balancing, scaling, application health monitoring and instance configuration are handled for you. - **Only the application code is your job.** But you keep **full control**: the resources are normal AWS resources in your account, and you can change their settings. - **Beanstalk is free.** You pay only for the resources it creates, such as the EC2 instances and load balancer. It sits between EC2 (you do everything) and fully serverless services (no servers at all): a *Platform as a Service* built on familiar pieces. ## Components [#components] - **Application:** the container for everything about one app: its environments, versions and saved configurations. - **Application version:** one iteration of your code, a source bundle (a zip, a Java WAR file) stored in S3, with a label such as `v1.4`. - **Environment:** the AWS resources running **one application version** at a time. You can have several environments, such as `dev`, `test` and `prod`, running different versions. - **Environment tier:** what kind of environment it is: a **web server** tier or a **worker** tier (below). - **Configuration:** the settings that define how the environment's resources behave. The workflow: **create an application → upload a version → launch an environment → manage it**, then upload new versions and deploy them to the environment. ### Supported platforms [#supported-platforms] Beanstalk runs code written in **Go, Java (SE and Tomcat), .NET (on Linux or Windows Server), Node.js, PHP, Python and Ruby**, and any language packaged as a **Docker** container, including a platform that runs containers on ECS. ## Web server tier vs worker tier [#web-server-tier-vs-worker-tier]
![The web server tier has a load balancer in front of web servers in an Auto Scaling group with an elasticbeanstalk.com URL; the worker tier has workers in an Auto Scaling group that take messages from an SQS queue, and the web tier can push jobs to it](/diagrams/compute-beanstalk-tiers.light.svg) ![The web server tier has a load balancer in front of web servers in an Auto Scaling group with an elasticbeanstalk.com URL; the worker tier has workers in an Auto Scaling group that take messages from an SQS queue, and the web tier can push jobs to it](/diagrams/compute-beanstalk-tiers.dark.svg)
Web tier for requests, worker tier for background jobs.
- **Web server tier:** a load balancer sends HTTP requests to EC2 instances in an Auto Scaling group across AZs. The environment gets a URL such as `myapp.us-east-1.elasticbeanstalk.com`. - **Worker tier:** EC2 instances in an Auto Scaling group process jobs from an **SQS queue**. Beanstalk creates the queue if you don't have one, and a daemon on each instance pulls messages and passes them to your app. The tier **scales on the number of messages** in the queue. - A web tier can **push jobs to the worker tier's queue**, so slow work (sending emails, making reports, resizing videos) doesn't hold up web requests. That's *decoupling*, covered in the [Application Integration](/docs/integration) group. ## Environment types [#environment-types]
![Single-instance environment with one EC2 instance, an Elastic IP and an RDS database in one AZ; high-availability environment with a load balancer, EC2 in an Auto Scaling group across two AZs, and RDS primary and standby](/diagrams/compute-beanstalk-modes.light.svg) ![Single-instance environment with one EC2 instance, an Elastic IP and an RDS database in one AZ; high-availability environment with a load balancer, EC2 in an Auto Scaling group across two AZs, and RDS primary and standby](/diagrams/compute-beanstalk-modes.dark.svg)
Single instance for dev, load-balanced for prod.
- **Single instance**, great for **development**: one EC2 instance with an **Elastic IP**, and optionally an RDS database, in one AZ. No load balancer, so it's cheap, but there's no failover or scaling. - **High availability with a load balancer**, great for **production**: a load balancer in front of an Auto Scaling group spanning several AZs, and an RDS database with a standby in a second AZ (Multi-AZ). You can start with a single instance and switch the environment to load-balanced later. Beanstalk now has two modes. **Beanstalk Standard** is what the slides describe: apps run on EC2. **Beanstalk Cluster** runs apps as containers on Amazon EKS. The platform list has also changed: the old *Multi-container Docker* and *Packer builder* platforms are gone, and Docker apps use the Docker or ECS platforms on Amazon Linux 2023. ## Real-world examples [#real-world-examples] - **A start-up** deploys its Python API with `eb deploy` from a laptop, and gets scaling and health monitoring without anyone on the team knowing CloudFormation. - **An agency** runs a `dev` single-instance environment and a `prod` load-balanced environment for each client site, from the same code. ## Exam tips [#exam-tips] - **"Developers want to deploy code without managing infrastructure", "quickly deploy a web app"**, on a supported language → Elastic Beanstalk. - **"Background jobs", "long-running tasks decoupled from the web app"** → a Beanstalk **worker** environment with SQS. - **"Cheap dev environment"** → single-instance environment. **"Production, highly available"** → load-balanced environment. - **Beanstalk itself is free**; you pay for the underlying resources. ## Common traps [#common-traps] - **"Beanstalk hides the resources so you can't change them."** They're normal resources in your account; you keep full control. - **"Beanstalk is serverless."** It runs EC2 instances (or EKS in Cluster mode) that you pay for.
Beyond the exam: deployment policies When you deploy a new version to a load-balanced environment, Beanstalk can roll it out in several ways: - **All at once:** fastest, but a short outage. - **Rolling:** one batch of instances at a time; capacity drops during the deploy. - **Rolling with additional batch:** launches an extra batch first, so capacity never drops. - **Immutable:** launches a full new set of instances, then swaps; safest and easiest to roll back. - **Traffic splitting:** sends a percentage of traffic to the new version first (canary testing). A **blue/green** deployment uses two environments and swaps their URLs. These are tested in the Developer Associate exam more than in SAA.
## Hands-on lab: deploy the sample app [#hands-on-lab-deploy-the-sample-app] **Goal:** get a working web app on AWS without writing code, and see what Beanstalk created. A single-instance environment runs one `t3.micro` with an Elastic IP: about **$0.02 an hour**. Beanstalk also creates a small S3 bucket for app versions. Terminate the environment when you finish. ### Create the application [#create-the-application] Open **Elastic Beanstalk** in us-east-1 and choose **Create application**. Environment tier **Web server environment**, application name `saa-beanstalk`, platform **Node.js** (latest), application code **Sample application**, preset **Single instance**. ### Roles [#roles] On **Configure service access**, choose **Create and use new service role**. For the **EC2 instance profile**, use `aws-elasticbeanstalk-ec2-role` if it exists. If not, the console shows a link to create it (an EC2 role with the `AWSElasticBeanstalkWebTier` policy). Pick your key pair `saa-lab-key`. ### Launch [#launch] Keep the defaults on the next pages (instance type `t3.micro`, no database), add the tag `Project=saa-lab`, and **Submit**. Watch the **Events** list as Beanstalk creates the resources, which takes a few minutes. ### Open it and look around [#open-it-and-look-around] When health is *OK*, click the environment's domain: the sample *Congratulations* page appears. Then look in the **EC2** console (a new instance and an Elastic IP) and **CloudFormation** (a stack named after the environment, which Beanstalk uses behind the scenes). **Expected result:** a running web app on its own `elasticbeanstalk.com` URL, built from normal EC2 resources in your account. **Clean up:** in Elastic Beanstalk, **Actions → Terminate environment**, then delete the application. Beanstalk removes the instance, Elastic IP and stack. The S3 bucket `elasticbeanstalk-us-east-1-` stays; empty and delete it if you won't use Beanstalk again (it has a bucket policy you may need to delete first). ## AWS documentation [#aws-documentation] - [What is AWS Elastic Beanstalk?](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/Welcome.html) - [Understanding concepts in Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.html) - [Elastic Beanstalk worker environments](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts-worker.html) - [Environment types](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features-managing-env-types.html) - [Elastic Beanstalk supported platforms](https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html) # Elastic network interfaces (/docs/compute/eni) ## What it is [#what-it-is] An [elastic network interface](/docs/glossary#term-eni) (ENI) is a **virtual network card** in a VPC. Every instance has at least one, and the instance's IP addresses and security groups actually belong to its ENIs. An ENI can have: - a **primary private IPv4** address, and one or more **secondary private IPv4** addresses; - one **Elastic IP** for each private IPv4 address; - one **public IPv4** address; - **IPv6** addresses; - one or more **security groups**; - a **MAC address**. An ENI lives in **one subnet**, so it's bound to **one Availability Zone**. ENIs have no extra charge. ## How it works [#how-it-works] - The **primary ENI** (`eth0`) is created with the instance and can't be detached. - You can create **secondary ENIs** on their own and **attach** or **detach** them while the instance is running. The number of ENIs an instance can have depends on its type. - An ENI keeps its IPs, security groups and MAC address when it moves. Moving it to another instance moves the traffic too. ### Failover with an ENI [#failover-with-an-eni]
![Inside one AZ, instance A's secondary interface eth1 with IP 10.0.0.42 and an Elastic IP is moved to standby instance B](/diagrams/compute-eni-failover.light.svg) ![Inside one AZ, instance A's secondary interface eth1 with IP 10.0.0.42 and an Elastic IP is moved to standby instance B](/diagrams/compute-eni-failover.dark.svg)
Moving a secondary ENI to a standby instance.
1. Instance A has its primary ENI `eth0` and a secondary ENI `eth1` with the private IP `10.0.0.42` and an Elastic IP. Clients connect to that IP. 2. Instance A fails. 3. You (or a script) detach `eth1` from A and attach it to standby instance B in the **same AZ**. 4. Clients keep using the same IP, now answered by B. No DNS change is needed. The same trick lets a software licence tied to a MAC address move to a new instance. ## Other uses [#other-uses] - **Two networks on one instance:** a management ENI in an admin subnet and a public ENI in a web subnet, each with its own security groups. - **Network appliances:** firewalls and load balancers with several interfaces. - **AWS services use ENIs too:** Lambda functions in a VPC, RDS databases and VPC endpoints all appear as ENIs in your subnets. If an ENI's description says it's *requester-managed*, an AWS service created it.
Beyond the exam: why ENIs matter for troubleshooting When you can't delete a subnet or security group, the cause is usually an ENI still using it, often one created by a service such as Lambda or a VPC endpoint. **EC2 → Network Interfaces**, filtered by subnet or security group, shows who owns it. VPC Flow Logs, covered in the VPC group, are also captured per ENI.
## Exam tips [#exam-tips] - **"Move a private IP (or MAC address) to a standby instance for failover"** → detach and attach a secondary ENI. - **"Instance in two subnets / dual-homed"** → attach a second ENI from the other subnet (same AZ). - **ENIs are tied to one AZ.** Failover by moving an ENI only works within that AZ. ## Common traps [#common-traps] - **"Move the ENI to an instance in another AZ."** An ENI can only attach to instances in its own AZ. - **"Detach the primary ENI."** Only secondary ENIs can be detached. ## Hands-on lab: move an ENI between instances [#hands-on-lab-move-an-eni-between-instances] **Goal:** create an ENI, attach it to one instance, then move it to another and see its IP follow. Two `t3.micro` instances with public IPs, about **$0.04 an hour** together. The ENI itself is free. ### Launch two instances in the same AZ [#launch-two-instances-in-the-same-az] Launch two `t3.micro` instances, `saa-eni-a` and `saa-eni-b`, with Amazon Linux 2023 and tag `Project=saa-lab`. In **Network settings → Edit**, pick the same subnet for both (for example the one in `us-east-1a`). ### Create an ENI [#create-an-eni] Open **Network & Security → Network Interfaces → Create network interface**: description `saa-eni`, the **same subnet**, IPv4 auto-assign, security group `default`. Note its private IP. ### Attach it to A [#attach-it-to-a] Select the ENI, **Actions → Attach**, choose `saa-eni-a`. On the instance's **Networking** tab, it now has two private IPs. ### Move it to B [#move-it-to-b] **Actions → Detach** (tick **force** if needed), then **Actions → Attach** to `saa-eni-b`. The same private IP now belongs to `saa-eni-b`. **Expected result:** the ENI's IP address moves from one instance to the other, and the primary interfaces never change. **Clean up:** terminate both instances, then delete the ENI in **Network Interfaces** (it's kept when the instance is terminated, because you created it separately). ## AWS documentation [#aws-documentation] - [Elastic network interfaces](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html) - [Network interface attachments for your EC2 instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/network-interface-attachments.html) - [Maximum IP addresses per network interface](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AvailableIpPerENI.html) # EC2 Hibernate (/docs/compute/hibernate) ## What it is [#what-it-is] When you **stop** an instance, its EBS disks are kept but its memory (RAM) is lost. When you start it again the operating system boots from scratch, then your applications start and fill their caches, which can take minutes. When you **terminate** it, the root volume is normally deleted as well. [Hibernation](/docs/glossary#term-hibernation) is a third option: the instance stops, but the **contents of its RAM are saved** first. On the next start the RAM is restored and every process carries on where it left off. The operating system isn't restarted, so the instance is ready much faster. ## How it works [#how-it-works]
![A running instance hibernates, saves its RAM to the encrypted root EBS volume, stops paying only for EBS, then on start reloads the RAM and resumes](/diagrams/compute-hibernate.light.svg) ![A running instance hibernates, saves its RAM to the encrypted root EBS volume, stops paying only for EBS, then on start reloads the RAM and resumes](/diagrams/compute-hibernate.dark.svg)
RAM goes to the root volume and comes back.
1. **Running:** applications and their data are in RAM. 2. **Hibernate:** EC2 tells the operating system to suspend to disk. It freezes all processes and writes the RAM contents to a file on the **root EBS volume**, then shuts down. 3. **Stopped:** you pay nothing for the instance, only for the EBS storage (which now includes the saved RAM). The public IPv4 address is released; private IPs and Elastic IPs stay. 4. **Start:** the instance boots, reads the RAM back from the root volume and unfreezes the processes. Applications resume with warm caches. **Use cases:** - long-running processes you want to pause and resume; - saving the in-memory state of a job; - services that take a long time to initialise, which you can *pre-warm* once and then hibernate until needed. ## Requirements [#requirements] - **Enable it at launch.** You can't turn hibernation on for an existing instance. - **Root volume:** must be **EBS** (not instance store), **encrypted**, and **large enough** to hold the RAM plus the OS and apps. Supported volume types are gp2, gp3, io1 and io2. - **RAM:** under **150 GiB** for Linux, **16 GiB or less** for Windows. - **Instance families:** most current general purpose, compute, memory and storage optimized families (for example M, C, R, I and T types). **Bare metal** instances aren't supported. - **AMIs:** Amazon Linux 2023, Amazon Linux 2, Ubuntu, RHEL and Windows Server, among others. - **Purchase options:** On-Demand (with or without RIs or Savings Plans) and Spot. For Spot, the request must be persistent. - **Duration:** an instance can stay hibernated for at most **60 days**. To keep it longer, start it, stop it, and start it again. - **Not in an Auto Scaling group or ECS:** Auto Scaling would mark the stopped instance unhealthy and replace it. The slides list only a few families (C3–C5, I3, M3–M4, R3–R4, T2, T3) and a single 150 GB limit. Hibernation now supports most current families, including Graviton types, and the RAM limit for **Windows** is 16 GiB. ## Exam tips [#exam-tips] - **"Keep the in-memory state", "faster boot", "applications take a long time to warm up"** → EC2 Hibernate. - **"Root volume must be…"** → EBS, encrypted, big enough for RAM. - **Limits:** RAM under 150 GiB (Linux), at most 60 days hibernated, enable at launch. ## Common traps [#common-traps] - **"Hibernate an instance that's already running without hibernation enabled."** It must be enabled at launch. - **"Hibernate with an instance store root volume."** Instance store data is lost on stop; the root must be EBS. - **"Hibernate instances in an Auto Scaling group to save money."** Not supported. ## Hands-on lab: hibernate and resume [#hands-on-lab-hibernate-and-resume] **Goal:** prove that the RAM, and the uptime counter, survive hibernation. One `t3.micro` with a public IP, about **$0.02 an hour** while running. While hibernated you pay only for the 8 GB volume. ### Launch with hibernation on [#launch-with-hibernation-on] **Launch instances**: name `saa-hibernate`, tag `Project=saa-lab`, Amazon Linux 2023, `t3.micro`, key pair `saa-lab-key`, security group `saa-web-sg`. Under **Configure storage → Advanced**, set the root volume's **Encrypted** to *Encrypted* (default key). Under **Advanced details**, set **Stop - Hibernate behavior** to *Enable*. Launch. ### Check the uptime [#check-the-uptime] Connect with **EC2 Instance Connect** and run `uptime`. Note how long it has been up. ### Hibernate [#hibernate] In the console choose **Instance state → Hibernate instance**. Wait until it's *Stopped*. ### Start and compare [#start-and-compare] Start the instance, connect again and run `uptime`. The uptime **continues** from before (plus a little), instead of starting near zero: the OS never rebooted. **Expected result:** after hibernate and start, `uptime` shows the original boot time, which proves the memory was restored. **Clean up:** terminate `saa-hibernate`. ## AWS documentation [#aws-documentation] - [Hibernate your Amazon EC2 instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) - [How Amazon EC2 instance hibernation works](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-hibernate-overview.html) - [Prerequisites for EC2 instance hibernation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hibernating-prerequisites.html) # Hybrid and edge compute (/docs/compute/hybrid-edge-compute) ## What it is [#what-it-is] Most workloads run in an AWS Region. Some can't: they need single-digit millisecond latency to users or factory machines, or the data must stay in a particular building or city by law. Many companies also run a **[hybrid cloud](/docs/glossary#term-hybrid-cloud)**: some systems on-premises, some in AWS, managed two different ways. AWS brings its compute closer to where it's needed in several ways: - **[AWS Outposts](/docs/glossary#term-aws-outposts):** AWS hardware installed **in your own data centre**. - **[Local Zones](/docs/glossary#term-local-zone):** small AWS sites **in large cities**, near your users. - **[Wavelength Zones](/docs/glossary#term-wavelength-zone):** AWS compute **inside telecom 5G networks**. - **VMware on AWS:** run your existing **VMware** environment on AWS hardware.
![From a Region to the edge: Region, Local Zone, Wavelength Zone, edge location](/diagrams/foundations-edge-options.light.svg) ![From a Region to the edge: Region, Local Zone, Wavelength Zone, edge location](/diagrams/foundations-edge-options.dark.svg)
Closer to the user means fewer services.
The [Global infrastructure](/docs/foundations/global-infrastructure#local-zones-and-wavelength-zones) page introduced Local Zones and Wavelength. This page looks at them, and at Outposts, as places to run EC2. ## AWS Outposts [#aws-outposts]
![An Outposts rack in your data centre talks to your servers through a local gateway and to its parent Region through a service link, sharing the same VPC](/diagrams/compute-outposts.light.svg) ![An Outposts rack in your data centre talks to your servers through a local gateway and to its parent Region through a service link, sharing the same VPC](/diagrams/compute-outposts.dark.svg)
An Outpost is part of a Region that lives in your building.
Outposts are **server racks** that AWS delivers, installs and manages in your data centre. They offer the **same AWS infrastructure, services, APIs and tools** as a Region, so you build on-premises applications exactly as you would in the cloud. 1. The **Outposts rack** runs AWS services locally: EC2, EBS, S3, ECS, EKS, RDS and EMR, among others. 2. It connects to your **own servers** and network through a **local gateway**, with very low latency. 3. A **service link** connects it back to its **parent Region**. The Outpost is an extension of one AZ: your VPC can have subnets on the Outpost and in the Region, and you manage it from the same console and APIs. **Benefits:** - **low-latency access** to on-premises systems; - **local data processing**; - **data residency**: data stays in your building; - **easier migration**: move apps to Outposts first, then to the Region; - **fully managed**: AWS monitors, patches and replaces the hardware. **Your responsibility:** the **physical security** of the rack, plus power, cooling and the network connection to the Region. (That's the shared responsibility model moving into your building.) Outposts come as **42U racks**. The smaller 1U and 2U Outposts servers are no longer sold to new customers. ## Local Zones [#local-zones] - An extension of a Region placed in a **large metro area**, such as Los Angeles or Lagos, for single-digit millisecond latency to people there. - Runs **EC2, EBS, some databases and other select services**. You opt in to the zone, then create a **subnet** in it in your existing VPC. - **Use cases:** real-time gaming, live streaming, virtual workstations and media editing, AR/VR, and meeting local **data residency** rules. ## Wavelength Zones [#wavelength-zones] - AWS compute and storage **inside a telecom provider's 5G network**, so traffic from phones doesn't leave the carrier's network. - Runs **EC2 and EBS** (plus services such as ECS, EKS and Auto Scaling). Traffic reaches it through a **carrier gateway**. - **Use cases:** apps for 5G devices needing ultra-low latency: connected vehicles, live video analytics, cloud gaming on phones, AR. ## VMware Cloud on AWS [#vmware-cloud-on-aws] Many companies run their data centres on **VMware vSphere**. They want more capacity, or to leave the data centre, without retraining staff or rebuilding every virtual machine. - **VMware Cloud on AWS** runs the VMware software stack (vSphere, vSAN, NSX) on dedicated AWS bare-metal servers. You manage it with the same vCenter tools as on-premises, and it can use AWS services such as EC2, S3, RDS, FSx and Direct Connect. - **Use cases:** migrate vSphere workloads to AWS, run production across private, public and hybrid VMware environments, and use AWS as a **disaster recovery** site. VMware Cloud on AWS is now sold by Broadcom, VMware's owner, rather than by AWS. AWS also launched **Amazon Elastic VMware Service (EVS)** in 2025, which runs VMware Cloud Foundation on bare-metal EC2 instances **inside your own VPC**, with your existing VCF subscription. For the exam, "keep using VMware tools while moving to AWS" still points to VMware Cloud on AWS. Also, Outposts *servers* (1U/2U) are no longer sold; Outposts racks are. ## Containers anywhere [#containers-anywhere] Two container options run on your own hardware, covered in the [Containers](/docs/containers) group: **Amazon ECS Anywhere** and **Amazon EKS Anywhere** manage containers on your servers with AWS tools, without AWS hardware. ## Exam tips [#exam-tips] - **"Run AWS services on-premises with the same APIs"**, **"data must stay in our data centre"**, **"low latency to on-premises systems"** → AWS Outposts. - **"Who handles physical security of an Outpost?"** → the customer. - **"Single-digit millisecond latency for users in a specific city"** → Local Zones. - **"Ultra-low latency for 5G mobile devices"** → Wavelength. - **"Extend or migrate a VMware vSphere data centre, keep using VMware tools"** → VMware Cloud on AWS. ## Common traps [#common-traps] - **"Outposts are managed and secured entirely by AWS."** AWS manages the hardware and services; you secure the site. - **"Local Zones run every AWS service."** Only a subset; the Region still runs the rest. - **"Use CloudFront for low-latency compute in a city."** CloudFront caches content; for running instances near users, use a Local Zone. ## Hands-on lab: find the edge zones near a Region [#hands-on-lab-find-the-edge-zones-near-a-region] **Goal:** list the Local Zones and Wavelength Zones attached to us-east-1, without creating anything. The *describe* API calls are free, and opting in to a zone is free too (but this lab doesn't opt in). ### List all zones of the Region [#list-all-zones-of-the-region] In **CloudShell** (us-east-1): ```bash aws ec2 describe-availability-zones --all-availability-zones \ --query "AvailabilityZones[].[ZoneName,ZoneType,OptInStatus,ParentZoneName]" \ --output table ``` ### Read the result [#read-the-result] Rows with type `availability-zone` are normal AZs. Rows with `local-zone` (names like `us-east-1-bos-1a`) and `wavelength-zone` (names like `us-east-1-wl1-...`) are the edge zones. Their **OptInStatus** shows whether your account has opted in, and **ParentZoneName** shows the AZ each one is tied to. **Expected result:** a list of the Local Zones and Wavelength Zones you could extend a VPC into from us-east-1. **Clean up:** nothing to delete. ## AWS documentation [#aws-documentation] - [What is AWS Outposts?](https://docs.aws.amazon.com/outposts/latest/userguide/what-is-outposts.html) - [What is AWS Local Zones?](https://docs.aws.amazon.com/local-zones/latest/ug/what-is-aws-local-zones.html) - [What is AWS Wavelength?](https://docs.aws.amazon.com/wavelength/latest/developerguide/what-is-wavelength.html) - [What is Amazon EVS?](https://docs.aws.amazon.com/evs/latest/userguide/what-is-evs.html) - [VMware Cloud on AWS](https://aws.amazon.com/vmware/) # Compute (/docs/compute) ## What it is [#what-it-is] *Compute* is the processing power that runs your code: CPU, memory and the network around them. AWS offers it at several levels. At one end you rent a whole virtual server and manage everything on it. At the other end you hand AWS a function and it runs it only when needed. This group covers **[Amazon EC2](/docs/glossary#term-amazon-ec2)** in depth, because almost every other service builds on it, plus the compute services that sit around it: Elastic Beanstalk, AWS Batch, the hybrid and edge options, and Compute Optimizer. Containers (ECS, EKS, Fargate) and Lambda have their own groups later. ## How the options compare [#how-the-options-compare]
![Compute options from more control to less to manage: EC2, Elastic Beanstalk, containers, Lambda](/diagrams/compute-options.light.svg) ![Compute options from more control to less to manage: EC2, Elastic Beanstalk, containers, Lambda](/diagrams/compute-options.dark.svg)
From more control to less to manage.
- **Amazon EC2** gives you virtual servers. You choose the operating system, install the software, patch it and decide how many servers run. Most control, most work. - **AWS Elastic Beanstalk** runs EC2 for you. You upload your code; Beanstalk creates the servers, load balancer and scaling, and you can still see and change them. - **Containers** (Amazon ECS, Amazon EKS, AWS Fargate) run your app packaged as a container image. With Fargate there are no servers to manage at all. - **AWS Lambda** runs a function when an event happens and bills by the millisecond. Nothing runs, and nothing is billed, when there's no work. **AWS Batch** doesn't fit on that line: it's a job scheduler that runs batch jobs on EC2, Spot or Fargate capacity for you. An online shop might use all of them. The legacy order system runs on EC2 because it needs a specific Windows version. The new storefront runs as containers on Fargate. Lambda resizes product photos when they're uploaded. Every night, AWS Batch rebuilds the product recommendations. ## In this group [#in-this-group] ### EC2 basics [#ec2-basics] ### Paying for EC2 [#paying-for-ec2] ### EC2 in depth [#ec2-in-depth] ### More compute [#more-compute] ## Which compute service for which job? [#which-compute-service-for-which-job] - **Lift an existing server to AWS as it is**, or you need full control of the OS → EC2. - **A standard web app, and the team doesn't want to manage servers** → Elastic Beanstalk. - **Microservices packaged as containers** → ECS or EKS, on Fargate if you don't want servers. - **Short tasks triggered by events** (a file upload, an API call, a message) → Lambda. - **Large batch jobs that run for hours**, such as nightly reports or simulations → AWS Batch. - **Must run in your own data centre** with AWS APIs → AWS Outposts. ## Exam tips [#exam-tips] - **"Least operational overhead"** usually rules EC2 out when a managed option works: Beanstalk, Fargate or Lambda. - **"Full control of the operating system"**, **"specific licensing"**, **"custom kernel"** → EC2. - **"Runs longer than Lambda's limit"**, **"needs a GPU"**, **"any runtime in a Docker image"** → Batch, ECS or EC2, not Lambda. - **"Lowest cost for fault-tolerant work"** → Spot Instances, often through Batch or an Auto Scaling group. ## AWS documentation [#aws-documentation] - [What is Amazon EC2?](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) - [Overview of compute services on AWS](https://docs.aws.amazon.com/whitepapers/latest/aws-overview/compute-services.html) - [Choosing an AWS compute service](https://docs.aws.amazon.com/decision-guides/latest/compute-on-aws-how-to-choose/choosing-aws-compute-service.html) # Instance types (/docs/compute/instance-types) ## What it is [#what-it-is] An [instance type](/docs/glossary#term-instance-type) decides the hardware your instance gets: how many virtual CPUs (vCPUs), how much memory, what network speed, and whether it has local disks or GPUs. AWS offers hundreds of types, grouped into families that are tuned for different kinds of work. Picking the right type matters for both cost and speed. A database short on memory is slow whatever you pay; a web server on a huge memory-optimized type wastes money every hour. ## The families [#the-families] - **General purpose** (M, T, Mac): a balance of compute, memory and networking. Web servers, code repositories, small databases, development machines. The course's `t2.micro` is one. - **Compute optimized** (C): fast processors for CPU-heavy work. Batch processing, media transcoding, high-performance web servers, scientific modelling, machine-learning inference, dedicated game servers. - **Memory optimized** (R, X, U, z): lots of RAM for data processed in memory. High-performance relational and NoSQL databases, in-memory caches, real-time analytics of big unstructured data, business-intelligence databases. - **Storage optimized** (I, D, Im, Is): fast local disks with very high read and write rates. High-frequency OLTP systems, NoSQL databases such as Cassandra, caches for in-memory databases like Redis, data warehousing, distributed file systems. - **Accelerated computing** (P, G, Inf, Trn, F, VT): GPUs or other chips for machine-learning training, graphics and video. - **HPC optimized** (Hpc): many cores and a fast network for large simulations, such as weather forecasting. ## How to read a type name [#how-to-read-a-type-name]
![The instance type m7g.2xlarge split into series m, generation 7, option g and size 2xlarge](/diagrams/compute-instance-type-name.light.svg) ![The instance type m7g.2xlarge split into series m, generation 7, option g and size 2xlarge](/diagrams/compute-instance-type-name.dark.svg)
Reading m7g.2xlarge.
1. **Series:** the first letter or letters give the family: `m` general purpose, `c` compute, `r` memory, `i` storage, `t` burstable, `p`/`g` GPU. 2. **Generation:** the number. Higher is newer, and newer generations usually give better performance for the same or a lower price. 3. **Options:** letters after the number. Common ones are `g` (AWS Graviton processor), `a` (AMD), `i` (Intel), `d` (local NVMe instance store disks), `n` (extra network bandwidth), `e` (extra memory or storage), `flex` (lower-cost flexible performance). 4. **Size:** after the dot: `nano`, `micro`, `small`, `medium`, `large`, `xlarge`, then `2xlarge` and up. Each size up roughly doubles the vCPUs, memory and price. `metal` means the whole physical server with no virtualisation. So `c7gn.4xlarge` is compute optimized, 7th generation, Graviton, extra networking, size 4xlarge. ### An example spread of types [#an-example-spread-of-types] The course compares five types. They show how much the families differ: | Instance | vCPU / memory | Network | | --- | --- | --- | | t2.micro | 1 / 1 GiB | low to moderate | | t2.xlarge | 4 / 16 GiB | moderate | | c5d.4xlarge | 16 / 32 GiB | up to 10 Gbps | | r5.16xlarge | 64 / 512 GiB | 20 Gbps | | m5.8xlarge | 32 / 128 GiB | 10 Gbps | Notice the `d` in `c5d`: it's the only one with a local disk, a 400 GB NVMe SSD. The others use only EBS volumes. And `r5` has four times the memory per vCPU of `c5d`. ## Burstable instances (the T family) [#burstable-instances-the-t-family] Many servers sit mostly idle and need full CPU only now and then. [Burstable instances](/docs/glossary#term-burstable-instance) (T4g, T3, T3a, and newer T8i and T9g) are built for that: - Each instance has a **baseline** CPU level, for example 10% of a vCPU. - When it runs below the baseline, it earns **CPU credits**. When it needs more, it spends credits to **burst** above the baseline. - In **standard** mode it slows back to the baseline when credits run out. In **unlimited** mode (the default for T3 and newer) it keeps bursting and you pay a small extra charge. They're the cheapest way to run small, spiky workloads such as test servers and low-traffic websites. A server that is busy all the time is cheaper on an M or C type. ## Processor choices [#processor-choices] The same family often comes in three processor versions: - **Intel** (`i`, or no letter on older types): the default; runs everything built for x86. - **AMD** (`a`): x86 too, usually about 10% cheaper. - **[AWS Graviton](/docs/glossary#term-aws-graviton)** (`g`): AWS's own Arm-based chips, with the best price-performance and lower energy use. Your software must be built for Arm (64-bit), which most Linux software, containers and managed runtimes already are. The slides list families up to the 6th generation. AWS now sells 7th and 8th generation types (and some 9th generation Graviton types), plus *flex* types. The way names work hasn't changed, and the exam doesn't test specific generations. ## Choosing a type [#choosing-a-type] 1. Start from the workload: is it limited by CPU, memory, disk or network? 2. Pick the family, then the smallest size that fits, on the newest generation. 3. Test it under real load. Billing is per second, so trying three types costs little. 4. Keep checking. [AWS Compute Optimizer](/docs/compute/compute-optimizer) reads your instances' metrics and recommends a smaller or bigger type. You can change an instance's type later: stop it, change the type, start it. ## Exam tips [#exam-tips] - **"In-memory database", "real-time big data in memory", "large cache"** → memory optimized (R, X). - **"Batch processing", "HPC", "media transcoding", "gaming servers"** → compute optimized (C). - **"High sequential read/write on local storage", "OLTP", "data warehousing"** → storage optimized (I, D). - **"Machine learning training", "GPU"** → accelerated computing (P, G, Trn). - **"Spiky, low average CPU", "cheapest for a small website"** → burstable T instances. - **"Best price-performance"** → Graviton (`g`) types, if the software runs on Arm. ## Common traps [#common-traps] - **"Change the instance type of a running instance."** You must stop it first (for EBS-backed instances). - **"Burstable instances give full CPU all the time."** Only up to the baseline, plus credits. - **"Graviton runs any software."** Only software built for Arm; a Windows x86 app won't run on it. ## Hands-on lab: explore instance types from the CLI [#hands-on-lab-explore-instance-types-from-the-cli] **Goal:** look up instance specifications and where they're available, without launching anything. The EC2 *describe* API calls and AWS CloudShell are free. ### Open CloudShell [#open-cloudshell] In the console, switch to **us-east-1** and open **CloudShell** (the terminal icon in the top bar). ### Compare two types [#compare-two-types] ```bash aws ec2 describe-instance-types --instance-types t3.micro m7g.2xlarge \ --query "InstanceTypes[].[InstanceType,VCpuInfo.DefaultVCpus,MemoryInfo.SizeInMiB,ProcessorInfo.SupportedArchitectures[0],NetworkInfo.NetworkPerformance]" \ --output table ``` You'll see `t3.micro` with 2 vCPUs, 1,024 MiB and `x86_64`, and `m7g.2xlarge` with 8 vCPUs, 32,768 MiB and `arm64`. ### List a family [#list-a-family] ```bash aws ec2 describe-instance-types \ --filters "Name=instance-type,Values=r7g.*" \ --query "sort_by(InstanceTypes,&MemoryInfo.SizeInMiB)[].[InstanceType,MemoryInfo.SizeInMiB]" \ --output table ``` The memory doubles with each size step. ### Check where a type is offered [#check-where-a-type-is-offered] ```bash aws ec2 describe-instance-type-offerings --location-type availability-zone \ --filters "Name=instance-type,Values=m7g.large" --output table ``` Not every type exists in every Availability Zone. This tells you which AZs have it. **Expected result:** you can read any type's vCPUs, memory, processor and network speed, and check where it's offered, before you pay for it. **Clean up:** nothing to delete. ## AWS documentation [#aws-documentation] - [Amazon EC2 instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) - [Amazon EC2 instance type naming conventions](https://docs.aws.amazon.com/ec2/latest/instancetypes/instance-type-names.html) - [Burstable performance instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) - [Amazon EC2 instance types (product page)](https://aws.amazon.com/ec2/instance-types/) # IP addressing (/docs/compute/ip-addressing) ## What it is [#what-it-is] Every device on a network needs an **IP address** so others can find it. There are two versions: - **IPv4**, such as `1.160.10.240`: four numbers from 0 to 255. It allows about 3.7 billion public addresses, which the world has nearly run out of. Still the most common. - **IPv6**, such as `3ffe:1900:4545:3:200:f8ff:fe21:67cf`: a much larger address space, useful for the Internet of Things and growing fast. The course, and most exam questions about EC2, use IPv4. ## Private vs public IP addresses [#private-vs-public-ip-addresses] - A **[public IP address](/docs/glossary#term-public-ip-address)** identifies a machine **on the internet**. It must be **unique worldwide**, and it can be roughly geo-located. - A **[private IP address](/docs/glossary#term-private-ip-address)** identifies a machine only **inside a private network**. It must be unique within that network, but two different companies can use the same private addresses. Only certain ranges are private: `10.0.0.0/8`, `172.16.0.0/12` and `192.168.0.0/16`. Machines with only a private IP reach the internet through a gateway that has a public IP (a [NAT device](/docs/vpc/nat-instance-nat-gateway)). That's how a whole office network can share one public address. ## IP addresses on an EC2 instance [#ip-addresses-on-an-ec2-instance] By default an instance in a default VPC gets: - a **private IPv4 address** from its subnet, used inside the AWS network; - a **public IPv4 address**, used to reach it from the internet. You SSH to the **public** IP, because your computer isn't on the same private network. The private IP is what other instances in the VPC use.
![Across a stop and start, the private IP stays the same; an auto-assigned public IP is released and replaced; an Elastic IP stays the same and is still billed](/diagrams/compute-ip-stop-start.light.svg) ![Across a stop and start, the private IP stays the same; an auto-assigned public IP is released and replaced; an Elastic IP stays the same and is still billed](/diagrams/compute-ip-stop-start.dark.svg)
What survives a stop and start.
- The **private IP stays** with the instance until it's terminated, through stops and starts. - An auto-assigned **public IP is released** when the instance stops (or hibernates), and the instance gets a **new** one when it starts. Anything that remembered the old address breaks. - An **Elastic IP** stays attached through a stop and start, so the public address never changes. You're still billed for it while the instance is stopped. ## Elastic IP addresses [#elastic-ip-addresses] An [Elastic IP address](/docs/glossary#term-elastic-ip-address) is a **static public IPv4 address** that belongs to your account until you release it. - You **allocate** it to your account, then **associate** it with one instance (or network interface) at a time. - You can **remap** it to another instance in seconds, which hides the failure of an instance or its software from users. - It belongs to **one Region**. - By default you can have **5 per Region** (you can ask for more). - It costs **$0.005 an hour** whether it's attached or not, like every public IPv4 address. ### Try to avoid Elastic IPs [#try-to-avoid-elastic-ips] Elastic IPs often point to a design that won't scale: one server that everyone connects to directly. Better options: - Give the instance a normal public IP and register a **DNS name** for it, updating the record when it changes. - Better still, put instances behind a **load balancer**, which has its own DNS name, and give the instances no public IP at all. Elastic IPs remain the right answer when something outside your control needs a fixed IP, such as a partner's firewall allow-list. Since February 2024 AWS charges **$0.005 an hour for every public IPv4 address**, attached or idle, Elastic or auto-assigned. Before, an Elastic IP attached to a running instance was free. That makes "avoid public IPs where you can" a cost point as well as a design one. ## Exam tips [#exam-tips] - **"Instance needs a fixed public IP that survives stop/start"** → Elastic IP. - **"Quickly move a public IP to a standby instance"** → remap the Elastic IP. - **"Public IP changed after restart"** → auto-assigned public IPs change on stop/start; use an Elastic IP, DNS or a load balancer. - **Private IPs don't change** when an instance stops and starts. ## Common traps [#common-traps] - **"Reboot changes the public IP."** A reboot keeps it; a stop and start doesn't. - **"An Elastic IP is free while attached."** All public IPv4 addresses are billed now. - **"Use an Elastic IP for each web server behind the load balancer."** The load balancer is the entry point; the servers don't need public IPs at all. ## Hands-on lab: watch the IPs change [#hands-on-lab-watch-the-ips-change] **Goal:** see the public IP change on stop and start, then fix it with an Elastic IP. The `saa-web` instance (about $0.02 an hour) plus an Elastic IP ($0.005 an hour). Release the Elastic IP at the end: an idle one keeps billing. ### Note the addresses [#note-the-addresses] Select `saa-web` in the EC2 console and note its **Private IPv4 address** and **Public IPv4 address**. ### Stop and start [#stop-and-start] Stop the instance, then start it. The private IP is the same; the public IP is different. ### Allocate an Elastic IP [#allocate-an-elastic-ip] Open **Network & Security → Elastic IPs → Allocate Elastic IP address**, keep the defaults, add the tag `Project=saa-lab`, and allocate. ### Associate it [#associate-it] Select the new address, choose **Actions → Associate Elastic IP address**, pick `saa-web` and associate. The instance's public IP is now the Elastic IP, and the web page loads on it. ### Stop and start again [#stop-and-start-again] Stop and start the instance once more. This time the public IP doesn't change. **Expected result:** an auto-assigned public IP changes on every stop and start; an Elastic IP doesn't. **Clean up:** **Actions → Disassociate Elastic IP address**, then **Actions → Release Elastic IP addresses**. Terminate `saa-web` if you're not doing more labs today. ## AWS documentation [#aws-documentation] - [Amazon EC2 instance IP addressing](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-instance-addressing.html) - [Elastic IP addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) - [Amazon VPC pricing (Public IPv4 Address tab)](https://aws.amazon.com/vpc/pricing/) # Placement groups (/docs/compute/placement-groups) ## What it is [#what-it-is] Normally EC2 decides which physical hardware your instances run on. A [placement group](/docs/glossary#term-placement-group) lets **you** influence that, when the placement matters for speed or for resilience. You create the group with a **strategy**, then launch instances into it. - **Cluster:** pack instances close together in one AZ, for the fastest network between them. - **Spread:** put each instance on separate hardware, so one hardware failure hits only one instance. - **Partition:** split instances into groups (partitions) on separate racks, for large distributed systems. - **Precision time:** place instances on hardware with very accurate clocks. Placement groups are **free**: you pay only for the instances. ## The three main strategies [#the-three-main-strategies]
![Cluster packs instances together in one AZ; spread puts each on its own rack, up to 7 per AZ; partition groups instances into up to 7 partitions per AZ with separate racks](/diagrams/compute-placement-groups.light.svg) ![Cluster packs instances together in one AZ; spread puts each on its own rack, up to 7 per AZ; partition groups instances into up to 7 partitions per AZ with separate racks](/diagrams/compute-placement-groups.dark.svg)
Speed, isolation, or both at scale.
### Cluster [#cluster] All instances sit close together in a **single AZ**, on the same high-bandwidth part of the network. - **Pros:** the lowest latency and highest throughput between instances: up to **10 Gbps per flow** with enhanced networking, against 5 Gbps outside a cluster group. - **Cons:** if the AZ (or that part of it) fails, **all instances fail together**. - **Use cases:** a big data job that must finish fast, HPC, any app needing very low latency between its nodes. - **Tips:** launch all instances in one request, with the same instance type, to avoid *insufficient capacity* errors. Burstable (T) types aren't supported. ### Spread [#spread] Each instance runs on **distinct hardware** (its own rack, with its own network and power). - **Pros:** can span **multiple AZs**; the lowest risk of instances failing at the same time. - **Cons:** **at most 7 running instances per AZ** per group. A Region with three AZs allows 21. - **Use cases:** a small number of critical instances that must stay isolated from each other, such as the primary and standby of an app, or a few domain controllers. ### Partition [#partition] The group is divided into **partitions**, and each partition has its **own set of racks**. No two partitions share racks. - **Up to 7 partitions per AZ**; can span multiple AZs in the Region. - **Hundreds of instances**: the number is limited only by your account's limits. - A rack failure can affect many instances, but **only within one partition**. - Instances can read which partition they're in from **instance metadata**, so *topology-aware* software can keep copies of data in different partitions. - **Use cases:** large distributed and replicated systems: HDFS, HBase, Cassandra, Kafka. ### Precision time [#precision-time] Places instances on hardware with direct access to high-precision time sources. - Instances get the **enhanced Amazon Time Sync Service**, more accurate than standard NTP. - On Linux they also get a **PTP hardware clock** and hardware packet timestamping, for microsecond-level clock sync. - **Use cases:** distributed databases that order transactions by time, financial trade timestamping, event ordering. - A cluster placement group can name a precision time group as its parent, giving both low latency and accurate clocks. The precision time strategy is new and appears only in the latest version of the slides. Cluster, spread and partition are the three the exam has always tested. ## How they compare [#how-they-compare] - **Need speed between instances?** Cluster. - **Need a few instances that never fail together?** Spread. - **Need hundreds of instances, with failures contained to a slice?** Partition. ## Exam tips [#exam-tips] - **"Low latency, high throughput between instances", "HPC", "tightly coupled"** → cluster placement group. - **"Critical instances must not share hardware", "maximise availability of a small number of instances"** → spread. - **"Hadoop / HDFS / Cassandra / Kafka", "large distributed workload aware of racks"** → partition. - **Limits:** spread = 7 instances per AZ per group; partition = 7 partitions per AZ; cluster = one AZ. ## Common traps [#common-traps] - **"Cluster placement group for high availability."** It's the opposite: everything is in one place. - **"A spread group with 20 instances in one AZ."** The maximum is 7 per AZ; use several groups. - **"A cluster group across AZs."** A cluster group is always in a single AZ. ## Hands-on lab: create placement groups [#hands-on-lab-create-placement-groups] **Goal:** create one of each main placement group and launch an instance into the spread group. Placement groups are free. The one `t3.micro` launched into the spread group costs about **$0.02 an hour** with its public IP. ### Create three groups [#create-three-groups] In the **EC2 console** (us-east-1), open **Network & Security → Placement Groups → Create placement group** three times: - `saa-cluster` with strategy **Cluster**; - `saa-spread` with strategy **Spread**, spread level **Rack**; - `saa-partition` with strategy **Partition** and **3** partitions. ### Launch into the spread group [#launch-into-the-spread-group] **Launch instances**: name `saa-pg`, Amazon Linux 2023, `t3.micro`, key pair `saa-lab-key`, an existing security group. In **Advanced details → Placement group**, choose `saa-spread`. Launch. ### Check the placement [#check-the-placement] Select the instance and open the **Details** tab: **Placement group** shows `saa-spread`. (A `t3.micro` can't go into `saa-cluster`: burstable types aren't supported in cluster groups, so that launch would fail.) **Expected result:** three placement groups and an instance running in the spread group. **Clean up:** terminate `saa-pg`, wait until it's terminated, then delete the three placement groups (a group can't be deleted while it holds instances). ## AWS documentation [#aws-documentation] - [Placement groups for your Amazon EC2 instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) - [Placement strategies for your placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-strategies.html) # Purchasing options (/docs/compute/purchasing-options) ## What it is [#what-it-is] The same EC2 instance can be paid for in several ways. They trade **flexibility** against **price**: commit to more, or accept interruptions, and you pay less. Choosing well is one of the biggest cost levers on AWS, and the exam asks about it in every cost question. - **[On-Demand](/docs/glossary#term-on-demand-instance):** pay by the second, no commitment. - **[Savings Plans](/docs/glossary#term-savings-plans):** commit to spending an amount per hour for 1 or 3 years. - **[Reserved Instances](/docs/glossary#term-reserved-instance):** commit to an instance configuration for 1 or 3 years. - **[Spot Instances](/docs/glossary#term-spot-instance):** spare capacity at a big discount, but AWS can take it back. - **[Dedicated Hosts](/docs/glossary#term-dedicated-host):** a whole physical server for you. - **[Dedicated Instances](/docs/glossary#term-dedicated-instance):** instances on hardware no other customer uses. - **[Capacity Reservations](/docs/glossary#term-capacity-reservation):** guaranteed capacity in one AZ, for as long as you need it. ## Choosing an option [#choosing-an-option]
![A decision flow: interruptible work goes to Spot, steady use to Savings Plans or RIs, server-bound licences to Dedicated Hosts, guaranteed AZ capacity to a Capacity Reservation, everything else to On-Demand](/diagrams/compute-purchasing-decision.light.svg) ![A decision flow: interruptible work goes to Spot, steady use to Savings Plans or RIs, server-bound licences to Dedicated Hosts, guaranteed AZ capacity to a Capacity Reservation, everything else to On-Demand](/diagrams/compute-purchasing-decision.dark.svg)
Ask the questions in order.
1. **Can the work be interrupted and restarted?** Batch jobs, data analysis, CI builds, stateless web servers behind a load balancer → **Spot**, the cheapest option. 2. **Will it run steadily for a year or more?** An always-on app or database → **Savings Plans** or **Reserved Instances**. 3. **Do software licences tie you to physical servers**, or do rules require your own hardware? → **Dedicated Hosts**. 4. **Must capacity be guaranteed in one AZ** for an event or a disaster-recovery plan? → **Capacity Reservation**, usually combined with a Savings Plan for the discount. 5. **None of the above**, or you can't predict usage yet → **On-Demand**. Real systems mix them: a baseline covered by Savings Plans, peaks on On-Demand, and fault-tolerant extra work on Spot. ## The options in detail [#the-options-in-detail] ### On-Demand Instances [#on-demand-instances] - Pay for what you use: **per second** (60-second minimum) for Linux and Windows, per hour for some other systems. - The **highest price**, but **no upfront payment** and **no commitment**. - Best for short-term, unpredictable workloads that mustn't be interrupted, and for trying things out. ### Reserved Instances (RIs) [#reserved-instances-ris] A Reserved Instance isn't a server. It's a **billing discount** applied to running instances that match its attributes. - **Up to 72%** off On-Demand. - You reserve specific attributes: **instance type, Region, tenancy and platform (OS)**. - **Term:** 1 year, or 3 years for a bigger discount. - **Payment:** No Upfront, Partial Upfront, or All Upfront. More upfront means a bigger discount. - **Scope:** *Regional* (discount applies in any AZ, no capacity reserved) or *zonal* (applies in one AZ and also **reserves capacity** there). - **Standard RIs:** the biggest discount; can be modified a little, and **sold** on the Reserved Instance Marketplace if you no longer need them. - **Convertible RIs:** up to 66% off; can be **exchanged** for different instance families, OS or tenancy, but **can't be sold** on the Marketplace. - You can't cancel an RI. When it expires you simply pay On-Demand again. - Good for steady-state use, such as a database that runs all year. ### Savings Plans [#savings-plans] You commit to a **spend per hour** (for example $10/hour) for 1 or 3 years. Usage up to that amount gets the discounted rate; anything above it is billed at On-Demand prices. - **Compute Savings Plans:** up to 66% off. Apply to EC2 in **any family, size, OS, tenancy or Region**, and also to **Fargate and Lambda**. The most flexible. - **EC2 Instance Savings Plans:** up to 72% off, the same as Standard RIs. Locked to **one instance family in one Region** (for example M7 in us-east-1), but flexible on size, OS and tenancy. - Two newer types cover other services: **Database Savings Plans** (up to 35% on RDS, Aurora, DynamoDB, ElastiCache and others) and **SageMaker AI Savings Plans**. - Same payment options as RIs. Spot usage isn't covered. ### Spot Instances [#spot-instances] - **Up to 90%** off, using EC2's spare capacity. - AWS can **reclaim the instance** with a **2-minute warning** when it needs the capacity back. - The most cost-efficient option, for workloads that can survive interruption: batch jobs, data analysis, image processing, distributed and containerised workloads, work with a flexible start and end time. - **Not** for critical jobs or databases. See [Spot Instances](/docs/compute/spot-instances) for the details. ### Dedicated Hosts [#dedicated-hosts] - A **physical server** with its EC2 capacity fully dedicated to you. - You see the **sockets and physical cores** and can keep instances on the same host over time (*host affinity*). That lets you **bring your own licence** (BYOL) for software licensed per socket, per core or per VM, such as Windows Server, SQL Server or Oracle. - Also used for strict **compliance** or regulatory requirements. - Pay On-Demand per host per second, or reserve for 1 or 3 years. The most expensive option. ### Dedicated Instances [#dedicated-instances] - Instances that run on hardware **dedicated to your account**. No other customer's instances share it. - They may share hardware with your **own** other instances, and you **don't control placement**: a stop and start can move them. - Billed per instance, plus a **$2 per hour** fee in each Region where you run at least one. Dedicated Host vs Dedicated Instance: | | Host | Instance | | --- | --- | --- | | Billing | per host | per instance | | Sockets and cores visible | yes | no | | Placement control | yes | no | | Per-core licences (BYOL) | yes | limited | ### Capacity Reservations [#capacity-reservations] - Reserve **On-Demand capacity in a specific AZ** for any duration, so instances can always launch when you need them. - **Immediate** reservations have no commitment: create and cancel any time. **Future-dated** reservations book capacity for a start date, with a minimum commitment. - **No discount:** you pay the On-Demand rate whether instances run in the reservation or not. Combine with **Regional RIs or Savings Plans** to get a discount. - Good for short, uninterrupted workloads that must be in one AZ: a product launch, a sale event, a disaster-recovery standby. - For GPU clusters for machine learning, **Capacity Blocks for ML** reserve GPU instances for a future date and length. ## How much each saves [#how-much-each-saves]
![Maximum discounts compared with On-Demand: Compute Savings Plans and Convertible RIs 66%, EC2 Instance Savings Plans and Standard RIs 72%, Spot 90%](/diagrams/compute-discounts.light.svg) ![Maximum discounts compared with On-Demand: Compute Savings Plans and Convertible RIs 66%, EC2 Instance Savings Plans and Standard RIs 72%, Spot 90%](/diagrams/compute-discounts.dark.svg)
Best-case discounts; real savings depend on type, term and payment.
More flexibility costs a little more: Compute Savings Plans and Convertible RIs save up to 66%, the more locked-in EC2 Instance Savings Plans and Standard RIs up to 72%, and Spot up to 90%, because you accept interruptions. Dedicated Hosts and Capacity Reservations start at the On-Demand price. The course compares them to a resort. **On-Demand:** turn up whenever you like and pay full price. **Reserved:** book a long stay in advance for a good discount. **Savings Plans:** pay a set amount per hour and stay in any room type. **Spot:** take an empty room very cheaply, but you can be asked to leave at short notice. **Dedicated Host:** book the whole building. **Capacity Reservation:** book a room at full price for a period, even if you don't sleep there. AWS now **recommends Savings Plans over Reserved Instances** for new purchases, because they give the same discount with more flexibility. Discount percentages change over time and the exam doesn't test exact numbers. Database Savings Plans and future-dated Capacity Reservations are newer than the slides. And Spot no longer works by bidding: AWS sets the Spot price, which moves slowly with supply and demand. ## Exam tips [#exam-tips] - **"Steady-state", "always on", "1 or 3 years"** → Savings Plans or Reserved Instances. - **"Flexibility across instance families, Regions, or Fargate and Lambda"** → Compute Savings Plans. - **"Change instance family during the term"** → Convertible RI or Compute Savings Plan, not Standard RI. - **"Fault-tolerant", "can be interrupted", "flexible timing", "cheapest"** → Spot. - **"Short-term, unpredictable, can't be interrupted"** → On-Demand. - **"BYOL per-socket / per-core licences", "control over the physical server"** → Dedicated Hosts. - **"Hardware not shared with other AWS accounts", no licence need** → Dedicated Instances. - **"Guarantee capacity in a specific AZ"** → On-Demand Capacity Reservation (or a zonal RI). ## Common traps [#common-traps] - **"Reserved Instances reserve capacity."** Only **zonal** RIs do. Regional RIs and Savings Plans are billing discounts only. - **"Capacity Reservations give a discount."** They don't; you pay On-Demand rates unless an RI or Savings Plan covers them. - **"Sell an unused Convertible RI on the Marketplace."** Only Standard RIs can be sold. - **"Use Spot for the production database."** A 2-minute warning isn't enough for a stateful database. - **"Dedicated Instances let me bring per-core licences."** That needs Dedicated Hosts. ## Hands-on lab: price one server four ways [#hands-on-lab-price-one-server-four-ways] **Goal:** see the real difference between purchasing options for the same instance. The AWS Pricing Calculator is free and creates nothing in your account. Don't buy Reserved Instances or Savings Plans to experiment: those purchases can't be cancelled. ### Open the calculator [#open-the-calculator] Go to [calculator.aws](https://calculator.aws/) and choose **Create estimate → Amazon EC2 → Configure**. Region **US East (N. Virginia)**. ### Describe the server [#describe-the-server] Operating system **Linux**, 1 instance, constant usage, 100% utilisation. Search the instance type `m7g.large`. ### Compare the payment options [#compare-the-payment-options] Under **Pricing strategy**, look at the monthly cost for **On-Demand**, then **Compute Savings Plans** (1 year, no upfront), **EC2 Instance Savings Plans** (3 years, all upfront) and **Spot**. Note each monthly figure. **Expected result:** four monthly prices for the same machine. Spot is far cheaper than On-Demand, and the 3-year EC2 Instance Savings Plan sits between them. **Clean up:** nothing to delete. You can save or discard the estimate. ## AWS documentation [#aws-documentation] - [Amazon EC2 billing and purchasing options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-purchasing-options.html) - [Reserved Instances for Amazon EC2 overview](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-reserved-instances.html) - [Savings Plans types](https://docs.aws.amazon.com/savingsplans/latest/userguide/plan-types.html) - [Amazon EC2 Dedicated Hosts](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-hosts-overview.html) - [Amazon EC2 Dedicated Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-instance.html) - [Reserve compute capacity with EC2 On-Demand Capacity Reservations](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-capacity-reservations.html) # Security groups (/docs/compute/security-groups) ## What it is [#what-it-is] A [security group](/docs/glossary#term-security-group) is a **virtual firewall** for an EC2 instance (strictly, for its network interfaces). It decides which traffic may reach the instance and which traffic may leave it. It's the most basic piece of network security in AWS, and every instance has at least one. A security group is just a list of **allow rules**: - **Inbound rules** control traffic coming **to** the instance: which protocol, which port, and from which source. - **Outbound rules** control traffic going **from** the instance to other places. - A source or destination can be an IP range (IPv4 or IPv6 CIDR), **another security group**, or a managed prefix list. There are **no deny rules**. Anything not allowed is blocked. ## How it works [#how-it-works]
![A security group allows port 22 from your computer, blocks it from another computer, and allows all outbound traffic](/diagrams/compute-sg-rules.light.svg) ![A security group allows port 22 from your computer, blocks it from another computer, and allows all outbound traffic](/diagrams/compute-sg-rules.dark.svg)
Inbound filtered by rules; outbound open by default.
1. Your computer connects to the instance on **port 22** (SSH). An inbound rule allows port 22 from your IP address, so the traffic gets through. 2. Another computer tries the same port. No rule names its IP, so the security group **drops** the traffic. The instance never sees it. 3. The instance connects out to the internet, for example to download updates. The default outbound rule allows all traffic, so it works. Security groups are **stateful**: if a request is allowed in, the reply is allowed out automatically, and the other way round. You don't write rules for return traffic. These rules come from a real security group. A table is the clearest way to show them, because that's how the console shows them too: | Rule | Source | Why | | --- | --- | --- | | HTTP 80 | 0.0.0.0/0 | public website | | SSH 22 | 203.0.113.25/32 | admin's IP | | TCP 4567 | 0.0.0.0/0 | Java app | All three rules use TCP. `0.0.0.0/0` means every IPv4 address; `/32` means exactly one address. ## Good to know [#good-to-know] - **One security group can be attached to many instances**, and one instance can have several security groups (5 per network interface by default, up to 16). The rules of all of them are combined. - **A security group belongs to one VPC in one Region.** You can also associate it with other VPCs in the same Region, or share it through a shared VPC. - **It lives outside the instance.** Blocked traffic never reaches the operating system, so the instance can't log or see it. - **A new security group** has no inbound rules (everything in is blocked) and one outbound rule allowing all traffic. - **Every VPC's default security group** allows inbound traffic from instances in the same group and all outbound traffic. Instances launched without choosing a group get it. - **Keep a separate security group for SSH access**, so admin access is easy to review and remove. - **A timeout means a security group problem.** If connecting just hangs, a rule is missing. - **"Connection refused" means the traffic arrived.** The application isn't running or isn't listening on that port. - **Quotas:** 60 inbound and 60 outbound rules per security group by default. - **Free:** security groups have no charge. The slides say a security group is locked to one Region and VPC. Since late 2024, *Security Group VPC Associations* let you associate a security group with other VPCs in the **same Region** and account (not the default security group or default VPC). It still can't cross Regions. For the exam, "a security group belongs to a VPC" remains the safe answer. ## Referencing other security groups [#referencing-other-security-groups] A rule's source can be **another security group** instead of an IP range. Then any instance that has that security group attached is allowed, whatever its IP address.
![The target instance's security group allows port 123 from security groups A and B; instances in A or B get through, an instance in C is blocked](/diagrams/compute-sg-referencing.light.svg) ![The target instance's security group allows port 123 from security groups A and B; instances in A or B get through, an instance in C is blocked](/diagrams/compute-sg-referencing.dark.svg)
Rules that name security groups, not IPs.
1. The target instance has **security group A**, whose inbound rules allow port 123 from security group A and from security group B. 2. An instance with **security group B** connects: allowed. 3. Another instance with **security group A** connects: allowed. A group can reference itself, so members can talk to each other. 4. An instance with **security group C** connects: blocked, because no rule names group C. *Why it matters:* instances come and go and their IPs change, especially with Auto Scaling. Referencing groups keeps the rules correct without listing IPs. The classic design is a chain: - The **load balancer's** security group allows 443 from the internet. - The **web servers'** security group allows 80 only from the load balancer's security group. - The **database's** security group allows 3306 only from the web servers' security group. Nobody on the internet can reach the web servers or database directly. ## Ports to know [#ports-to-know] - **22, SSH** (Secure Shell): log in to a Linux instance. - **21, FTP** (File Transfer Protocol): upload files to a file share. - **22, SFTP** (SSH File Transfer Protocol): upload files over SSH. - **80, HTTP**: unencrypted websites. - **443, HTTPS**: encrypted websites. - **3389, RDP** (Remote Desktop Protocol): log in to a Windows instance. Database ports such as 3306 (MySQL) and 5432 (PostgreSQL) come up in the [Databases](/docs/databases/rds-security-proxy#network-and-access) group. ## Real-world examples [#real-world-examples] - **A three-tier web app** uses the chain above, so the database accepts connections only from the app servers. - **An admin team** keeps one `ssh-from-office` security group with the office's IP range, attached only to the servers that need it. ## Exam tips [#exam-tips] - **"Instance must accept traffic only from the load balancer"** → web servers' security group references the load balancer's security group. - **"Connection times out"** → security group (or network ACL) rule missing. **"Connection refused"** → the application. - **Security groups are stateful and allow-only.** Need to **deny** a specific IP? That's a [network ACL](/docs/vpc/nacl-vs-security-groups). - **"Allow SSH only from the company network"** → inbound rule on port 22 with the company's CIDR, not `0.0.0.0/0`. ## Common traps [#common-traps] - **"Add a deny rule to the security group."** There are none; use a network ACL. - **"Add an outbound rule for the response traffic."** Not needed: security groups are stateful. - **"A security group is attached to a subnet."** It's attached to instances (network interfaces). Network ACLs are the subnet-level firewall. ## Hands-on lab: timeout vs connection refused [#hands-on-lab-timeout-vs-connection-refused] **Goal:** change security group rules and see the two kinds of failure for yourself. Uses the `saa-web` instance from the [EC2 basics lab](/docs/compute/ec2-basics#hands-on-lab-launch-a-web-server-with-user-data), about **$0.02 an hour**. If you terminated it, launch it again the same way. ### Break the website [#break-the-website] Open **EC2 → Security Groups → saa-web-sg → Inbound rules → Edit inbound rules**. Delete the **HTTP** rule and save. Reload `http://` in a private browser window: it spins and then **times out**. ### Fix it [#fix-it] Add the rule back: type **HTTP**, source **Anywhere-IPv4** (`0.0.0.0/0`). The page loads again straight away, with no restart: rule changes apply immediately. ### Try a port with nothing listening [#try-a-port-with-nothing-listening] Open `http://:8080`. It times out: no rule allows 8080. Now add an inbound rule **Custom TCP, port 8080, source My IP** and try again. This time the browser reports **connection refused** almost instantly: the traffic reached the instance, but no program listens on 8080. ### Look at the outbound rules [#look-at-the-outbound-rules] Open the **Outbound rules** tab: one rule allows all traffic to `0.0.0.0/0`. That's why the user data script could download the web server. **Expected result:** a timeout when a rule is missing, and a fast *connection refused* when the port is open but nothing is listening. **Clean up:** delete the port 8080 rule. Keep `saa-web` for the [Connecting to EC2](/docs/compute/connecting-to-ec2) lab, or terminate it. ## AWS documentation [#aws-documentation] - [Control traffic to your AWS resources using security groups](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html) - [Security group rules](https://docs.aws.amazon.com/vpc/latest/userguide/security-group-rules.html) - [Default security groups for your VPCs](https://docs.aws.amazon.com/vpc/latest/userguide/default-security-group.html) - [Associate security groups with multiple VPCs](https://docs.aws.amazon.com/vpc/latest/userguide/security-group-assoc.html) - [Amazon VPC quotas](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) # Spot Instances (/docs/compute/spot-instances) ## What it is [#what-it-is] A [Spot Instance](/docs/glossary#term-spot-instance) runs on EC2 capacity that nobody is using right now, for **up to 90% less** than On-Demand. The catch: when AWS needs that capacity back for On-Demand customers, it **interrupts** your instance with a **2-minute warning**. Spot exists because AWS must keep spare capacity for sudden demand. Rather than leave it idle, AWS sells it cheaply to work that can tolerate being stopped. ## How Spot pricing works [#how-spot-pricing-works] - Each instance type in each AZ (a *Spot capacity pool*) has its own **Spot price**. - **AWS sets the Spot price**, and it moves **slowly**, based on long-term supply and demand. You pay the current Spot price, never more than the On-Demand price. - You can set a **maximum price**. If the Spot price rises above it, your instance is interrupted. AWS advises not setting one: instances with a maximum price are interrupted more often. - The console shows **Spot price history** for the last three months, per AZ. The most common reason for interruption isn't price, though. It's AWS needing the capacity back. ## Spot requests and interruptions [#spot-requests-and-interruptions]
![A Spot request launches a Spot Instance; when interrupted after a 2-minute warning, a persistent request relaunches and a one-time request closes; to stop, cancel the request and then terminate the instances](/diagrams/compute-spot-requests.light.svg) ![A Spot request launches a Spot Instance; when interrupted after a 2-minute warning, a persistent request relaunches and a one-time request closes; to stop, cancel the request and then terminate the instances](/diagrams/compute-spot-requests.dark.svg)
A Spot request's life, and how to end it.
1. You create a **Spot request**: how many instances, which type and AZ, and the request type. - **One-time:** once the instance is launched and later ends, the request closes. - **Persistent:** the request stays open. After an interruption, it launches a new instance when capacity is back. 2. When capacity is available, EC2 launches the **Spot Instance**, which runs at the Spot price. 3. When AWS needs the capacity, it sends a **2-minute interruption notice** (an EventBridge event and an instance metadata item), then **interrupts** the instance. 4. The **interruption behaviour** you chose decides what happens: **terminate** (the default), **stop**, or **hibernate**. Stop and hibernate need a persistent request. AWS also sends an earlier signal, the **rebalance recommendation**, when an instance is at higher risk, so you can move work before the 2-minute notice. ### Stopping Spot Instances for good [#stopping-spot-instances-for-good] **Cancelling a Spot request doesn't terminate its running instances.** And terminating instances of a persistent request just makes it launch new ones. So the order matters: 1. **Cancel the Spot request** first. You can cancel requests that are open, active or disabled. 2. Then **terminate** the instances it launched. ## Fleets: many Spot Instances at once [#fleets-many-spot-instances-at-once] A single Spot request asks for one instance type in one pool. If that pool runs out, you get nothing. **Fleets** ask for a target capacity across **many pools** (instance types × AZs), and can mix Spot and On-Demand. - **Spot Fleet** (in the slides): a set of Spot Instances plus optional On-Demand Instances. It tries to meet the target capacity within your price limits, choosing from the launch pools you define, and stops launching when it reaches the capacity or the maximum cost. - **[EC2 Fleet](/docs/glossary#term-ec2-fleet):** the newer API with the same features, used from the CLI. - **Auto Scaling groups** with mixed instance types: what AWS recommends for most fleets, because they add health checks, load balancer integration and scaling. See [Auto Scaling groups](/docs/scaling/auto-scaling-groups#what-a-group-needs). ### Allocation strategies [#allocation-strategies] How a fleet chooses which pools to launch Spot Instances from: - **priceCapacityOptimized (recommended):** picks the pools with the most spare capacity, then the cheapest of those. Fewest interruptions at a low price. Best for most workloads. - **capacityOptimized:** picks the pools with the most spare capacity. Good when restarting work is expensive. - **diversified:** spreads instances across all pools. Good for availability and long-running work. - **lowestPrice:** uses the cheapest pools. Highest interruption risk; AWS no longer recommends it. AWS now calls Spot Fleet a **legacy API with no planned investment**. It recommends Auto Scaling groups, or EC2 Fleet when you manage the instances yourself. The allocation strategies are the same in all three. The `lowestPrice` strategy is marked *not recommended*. ## Real-world examples [#real-world-examples] - **A film studio** renders frames on 2,000 Spot Instances overnight. If some are interrupted, those frames are simply re-queued. - **A data team** runs Spark jobs on EMR with Spot task nodes, cutting the cluster bill by 70%. - **A CI system** runs build agents on Spot. An interrupted build just restarts. ## Exam tips [#exam-tips] - **"Cheapest", "fault-tolerant", "can be interrupted", "flexible start and end time"** → Spot. - **"2-minute warning"** → Spot interruption notice; handle it with an EventBridge rule or by checking instance metadata. - **"Stop Spot Instances and stop new ones launching"** → cancel the request, then terminate the instances. - **"Launch Spot across many instance types and AZs with the fewest interruptions"** → a fleet or Auto Scaling group with **price-capacity-optimized** allocation. - **"Mix On-Demand for the baseline and Spot for extra capacity"** → a fleet or Auto Scaling group with mixed purchase options. ## Common traps [#common-traps] - **"Spot for a database or a critical job."** No: it can disappear with 2 minutes' notice. - **"Terminate the instances to end a persistent request."** The request just relaunches them; cancel it first. - **"Bid high to keep your instance."** There's no bidding, and setting a maximum price can only increase interruptions. ## Hands-on lab: launch and end a Spot Instance [#hands-on-lab-launch-and-end-a-spot-instance] **Goal:** check Spot prices, launch a Spot Instance from the normal launch wizard, and end it properly. A Spot `t3.micro` costs well under a cent an hour, plus $0.005 an hour for its public IPv4 address. Finish within the hour and the lab costs a few cents. ### Look at the price history [#look-at-the-price-history] In the **EC2 console** (us-east-1), open **Spot Requests → Pricing history**. Choose instance type `t3.micro`, platform Linux/UNIX, last 3 months. Note the price per AZ compared with the On-Demand line. ### Launch a Spot Instance [#launch-a-spot-instance] Choose **Launch instances**: name `saa-spot`, tag `Project=saa-lab`, Amazon Linux 2023, `t3.micro`, key pair `saa-lab-key`, security group `saa-web-sg` (or a new one). Open **Advanced details → Purchasing option**, tick **Spot instances**, and keep the default settings (no maximum price, one-time request). Launch. ### Find the request [#find-the-request] Open **Spot Requests**. Your request shows *fulfilled* and the instance ID. In **Instances**, the instance's **Lifecycle** column (add it with the gear icon if hidden) says *spot*. ### End it [#end-it] Terminate the instance. Back in **Spot Requests**, the one-time request is now *closed*: there's nothing more to cancel. (With a persistent request, you'd cancel the request first, then terminate.) **Expected result:** a working instance at Spot prices, launched exactly like an On-Demand one, and a closed request after you terminate it. **Clean up:** make sure **Spot Requests** shows no *open* or *active* requests and the instance is terminated. ## AWS documentation [#aws-documentation] - [Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html) - [Spot Instance interruptions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html) - [Spot Instance interruption notices](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-instance-termination-notices.html) - [Which is the best fleet method to use?](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/which-fleet-method-to-use.html) - [Allocation strategies for EC2 Fleet and Spot Fleet](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-allocation-strategy.html) # Amazon ECR (/docs/containers/ecr) ## What it is [#what-it-is] **[Amazon ECR](/docs/glossary#term-amazon-ecr)** (Elastic Container Registry) **stores and manages Docker (container) images** on AWS.
![Amazon ECR: a private repository stores versions of an image, such as web:1.4 and web:1.5, with scan on push, lifecycle rules and replication; an ECS cluster pulls the images, allowed by its IAM role](/diagrams/containers-ecr.light.svg) ![Amazon ECR: a private repository stores versions of an image, such as web:1.4 and web:1.5, with scan on push, lifecycle rules and replication; an ECS cluster pulls the images, allowed by its IAM role](/diagrams/containers-ecr.dark.svg)
A private registry that ECS pulls from.
- **Private** repositories, and **public** ones published in the **Amazon ECR Public Gallery** (gallery.ecr.aws). - **Fully integrated with ECS** (and EKS), and **backed by Amazon S3**, so images are stored durably. - **Access is controlled through IAM**. If ECS can't pull an image, check the IAM policy of the instance profile or task execution role (`ecr:GetAuthorizationToken`, `ecr:BatchGetImage`…). - Supports: - **image vulnerability scanning**: *basic* scanning for operating system CVEs, on push or manually; *enhanced* scanning with **Amazon Inspector** for OS and programming-language packages, continuously; - **versioning** with image **tags** (and immutable tags, so a tag can't be overwritten); - **lifecycle policies** that delete old or untagged images automatically; - **replication** to other Regions and accounts; - **pull through cache**, which keeps copies of public images (such as from Docker Hub) in your private registry. ## Real-world examples [#real-world-examples] - **A CI pipeline** builds an image on every merge and pushes it to ECR with the commit hash as tag; ECS deploys that tag. - **A security team** turns on enhanced scanning and gets an EventBridge alert when a new CVE affects a running image. - **A team** keeps only the last 20 images per repository with a lifecycle policy, to control storage costs. ## Exam tips [#exam-tips] - **"Private Docker registry on AWS"** → Amazon ECR. - **"ECS tasks can't pull the image"** → IAM permissions (instance profile or task execution role). - **"Scan container images for vulnerabilities"** → ECR image scanning (enhanced = Amazon Inspector). - **"Delete old images automatically"** → ECR lifecycle policy. - **"Images available in another Region for DR"** → ECR cross-Region replication. ## Common traps [#common-traps] - **"ECR images are public by default."** Private repositories are private; access is through IAM. - **"ECR scanning needs a third-party tool."** Basic scanning is built in; enhanced uses Amazon Inspector. ## Hands-on lab: push an image to ECR [#hands-on-lab-push-an-image-to-ecr] **Goal:** create a private repository and push an image from CloudShell. ECR storage costs $0.10 per GB-month; a small image for a day costs **far less than a cent**. Any Region works. ### Create a repository [#create-a-repository] **ECR → Private registry → Repositories → Create repository**. Name `saa-hello`, turn on **Scan on push**. Create. ### Push an image [#push-an-image] Open the repository and choose **View push commands**. In CloudShell (which has Docker), run them, using a public image instead of building one: ```bash aws ecr get-login-password | docker login --username AWS --password-stdin .dkr.ecr..amazonaws.com docker pull public.ecr.aws/docker/library/hello-world:latest docker tag public.ecr.aws/docker/library/hello-world:latest .dkr.ecr..amazonaws.com/saa-hello:v1 docker push .dkr.ecr..amazonaws.com/saa-hello:v1 ``` ### Look at the result [#look-at-the-result] Refresh the repository: image tag `v1` appears, and after a moment its **scan status** shows the findings (probably none for this tiny image). **Expected result:** your own private copy of an image, scanned on push. **Clean up:** delete the `saa-hello` repository (choose to delete its images too). ## AWS documentation [#aws-documentation] - [What is Amazon ECR?](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) - [Scan images for software vulnerabilities](https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html) - [Automate the cleanup of images with lifecycle policies](https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html) - [Private image replication in Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/replication.html) # ECS scaling and patterns (/docs/containers/ecs-scaling-patterns) ## ECS Service Auto Scaling [#ecs-service-auto-scaling] **[ECS Service Auto Scaling](/docs/glossary#term-ecs-service-auto-scaling)** automatically increases or decreases the **desired number of ECS tasks** in a service. - It uses **[Application Auto Scaling](/docs/scaling/scaling-policies#aws-auto-scaling-and-application-auto-scaling)**, on metrics such as: - the service's average **CPU** utilization; - the service's average **memory** utilization (scale on RAM); - **ALB request count per target**, a metric from the load balancer. - Policy types: - **target tracking:** keep a CloudWatch metric near a target value; - **step scaling:** scale in steps when a CloudWatch alarm fires; - **scheduled scaling:** scale at set dates and times, for predictable changes. - **ECS Service Auto Scaling (task level) ≠ EC2 Auto Scaling (instance level).** - Fargate auto scaling is much **easier to set up**, because it's serverless: there's no instance level. ## Scaling the EC2 capacity [#scaling-the-ec2-capacity]
![Two levels of ECS scaling: when the service's average CPU goes above the target, a CloudWatch alarm makes ECS Service Auto Scaling add tasks; on the EC2 launch type, a capacity provider then adds EC2 instances to the Auto Scaling group when there is not enough capacity](/diagrams/containers-ecs-scaling.light.svg) ![Two levels of ECS scaling: when the service's average CPU goes above the target, a CloudWatch alarm makes ECS Service Auto Scaling add tasks; on the EC2 launch type, a capacity provider then adds EC2 instances to the Auto Scaling group when there is not enough capacity](/diagrams/containers-ecs-scaling.dark.svg)
More tasks first, then more instances to hold them.
On the EC2 launch type, new tasks need room. Add EC2 instances to fit them: - **Auto Scaling group scaling:** scale the ASG on CPU utilization, adding instances over time. Simple, but it doesn't know what ECS needs. - **[ECS capacity provider](/docs/glossary#term-ecs-capacity-provider)** (better): - automatically **provisions and scales the infrastructure** for your ECS tasks; - a capacity provider is **paired with an Auto Scaling group**; - it **adds EC2 instances when ECS is missing capacity** (CPU, RAM…) to place tasks. Capacity providers also exist for **Fargate**, **Fargate Spot** and ECS Managed Instances. A **capacity provider strategy** spreads tasks across them, for example a base on Fargate and extra tasks on Fargate Spot. ## Event-driven patterns [#event-driven-patterns] ### ECS tasks run by EventBridge [#ecs-tasks-run-by-eventbridge]
![An event-driven ECS task: a client uploads a file to Amazon S3; the object-created event reaches EventBridge, whose rule runs a new Fargate task; the task, using its task role, reads the object from S3 and saves the result to DynamoDB](/diagrams/containers-ecs-eventbridge.light.svg) ![An event-driven ECS task: a client uploads a file to Amazon S3; the object-created event reaches EventBridge, whose rule runs a new Fargate task; the task, using its task role, reads the object from S3 and saves the result to DynamoDB](/diagrams/containers-ecs-eventbridge.dark.svg)
An upload starts a container that does the work.
1. A client uploads an object to an **S3 bucket**. 2. S3 sends an event to **[EventBridge](/docs/integration/eventbridge)**, where a rule **runs an ECS task** (on Fargate, in your VPC). 3. The new task, with a **task role** allowing S3 and DynamoDB, gets the object, processes it and saves the result to **DynamoDB**. ### ECS tasks on an EventBridge schedule [#ecs-tasks-on-an-eventbridge-schedule] An EventBridge schedule (for example **every hour**) runs an ECS task on Fargate that does **batch processing**, such as working through files in S3. You pay only while the task runs. ### Queue workers and stopped tasks [#queue-workers-and-stopped-tasks]
![Two ECS patterns: queue workers, where an ECS service polls an SQS queue and scales its tasks on the queue length; and alerting on stopped tasks, where an ECS task state change to STOPPED is sent through EventBridge to an SNS email for an administrator](/diagrams/containers-ecs-patterns.light.svg) ![Two ECS patterns: queue workers, where an ECS service polls an SQS queue and scales its tasks on the queue length; and alerting on stopped tasks, where an ECS task state change to STOPPED is sent through EventBridge to an SNS email for an administrator](/diagrams/containers-ecs-patterns.dark.svg)
Workers on a queue, and an alert when a task stops.
- **SQS queue example:** an ECS service's tasks **poll an [SQS queue](/docs/integration/sqs)** for messages, and **ECS Service Auto Scaling** adds tasks as the queue grows. - **Intercept stopped tasks:** ECS sends task state changes to EventBridge. A rule matching tasks whose `lastStatus` is **`STOPPED`** (for example *Essential container in task exited*) triggers an **SNS** email to an administrator. ## Real-world examples [#real-world-examples] - **A video platform** keeps its web service at 60% average CPU with target tracking; a capacity provider adds EC2 instances when tasks have nowhere to go. - **A document service** starts a Fargate task for each uploaded PDF through EventBridge, extracting text into DynamoDB. - **A nightly job** runs a container on an EventBridge schedule at 01:00 instead of keeping a server running all day. ## Exam tips [#exam-tips] - **"Scale the number of ECS tasks on CPU, memory or ALB requests"** → ECS Service Auto Scaling. - **"Add EC2 instances automatically when tasks can't be placed"** → ECS capacity provider with an Auto Scaling group. - **"Run a container when a file lands in S3"** → S3 event → EventBridge rule → ECS task. - **"Run a container every hour"** → EventBridge schedule → ECS task (Fargate). - **"Process messages from a queue with containers, scaling with the backlog"** → ECS service + SQS + Service Auto Scaling. - **"Notify when a container stops unexpectedly"** → ECS task state change event → EventBridge → SNS. ## Common traps [#common-traps] - **"Service Auto Scaling also adds EC2 instances."** It adds tasks; capacity providers (or ASG scaling) add instances. - **"Fargate needs an Auto Scaling group."** Fargate has no instances to scale. ## Check yourself [#check-yourself] Add an ECS capacity provider linked to the cluster's Auto Scaling group, with managed scaling, so ECS adds EC2 instances when tasks can't be placed. S3 event to EventBridge, with a rule that runs an ECS task on Fargate; give the task a task role for S3 and wherever it writes results. ## AWS documentation [#aws-documentation] - [Automatically scale your Amazon ECS service](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-auto-scaling.html) - [Amazon ECS clusters and capacity providers](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html) - [Using EventBridge Scheduler to schedule ECS tasks](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/scheduled_tasks.html) - [Amazon ECS events and EventBridge](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwe_events.html) # Amazon ECS (/docs/containers/ecs) ## What it is [#what-it-is] **[Amazon ECS](/docs/glossary#term-amazon-ecs)** (Elastic Container Service) runs Docker containers on AWS. Launching containers on ECS means launching **ECS tasks** on **ECS clusters**: - A **task definition** describes one or more containers: the image, CPU and memory, ports, environment variables, IAM role, volumes. - A **task** is a running copy of a task definition. - A **service** keeps a set number of tasks running (replacing failed ones) and can put them behind a load balancer. - A **cluster** is the group of capacity your tasks run on. ## Where tasks run [#where-tasks-run]
![Three ways to run ECS tasks: with the EC2 launch type you manage the instances, each running the ECS agent; with Fargate there are no instances and you pay for each task's CPU and memory; with ECS Managed Instances, AWS manages the EC2 instances for you, with a choice of instance types](/diagrams/containers-ecs-capacity.light.svg) ![Three ways to run ECS tasks: with the EC2 launch type you manage the instances, each running the ECS agent; with Fargate there are no instances and you pay for each task's CPU and memory; with ECS Managed Instances, AWS manages the EC2 instances for you, with a choice of instance types](/diagrams/containers-ecs-capacity.dark.svg)
Three kinds of capacity for the same tasks.
### EC2 launch type [#ec2-launch-type] - **You provision and maintain the infrastructure**: the EC2 instances. - Each instance runs the **ECS agent**, which registers it in the ECS cluster. - AWS takes care of starting and stopping containers on them. ### Fargate launch type [#fargate-launch-type] - Launch Docker containers on AWS **without provisioning any infrastructure**: no EC2 instances to manage. - **It's all serverless.** You just create task definitions, and AWS runs the tasks for you based on the **CPU and RAM** you ask for. - **To scale, just increase the number of tasks.** No more EC2 instances to think about. - **Fargate Spot** runs fault-tolerant tasks on spare capacity at a discount. ### ECS Managed Instances [#ecs-managed-instances] - **AWS manages EC2 instances for you**: provisioning, scaling and security patching, using AWS-owned AMIs. - Unlike Fargate, you can choose from a **wide range of EC2 instance types** (for example GPU instances). - No SSH and no custom AMIs; instances are replaced at least every 14 days to keep them patched. **[AWS Fargate](/docs/glossary#term-aws-fargate)** is the default answer when a question says "no servers to manage". The EC2 launch type gives the most control (custom AMIs, specific instances, Reserved Instances or Savings Plans on the hosts). ## IAM roles for ECS [#iam-roles-for-ecs]
![IAM roles for ECS: on the EC2 launch type the ECS agent uses the instance profile to register with ECS, pull images from ECR and send logs to CloudWatch; each task gets its own task role, so task A can reach Amazon S3 and task B can reach DynamoDB](/diagrams/containers-ecs-roles.light.svg) ![IAM roles for ECS: on the EC2 launch type the ECS agent uses the instance profile to register with ECS, pull images from ECR and send logs to CloudWatch; each task gets its own task role, so task A can reach Amazon S3 and task B can reach DynamoDB](/diagrams/containers-ecs-roles.dark.svg)
One role for the agent, one per task for the app.
- **EC2 instance profile** (EC2 launch type only), used by the **ECS agent** to: - make API calls to the ECS service; - send container logs to CloudWatch Logs; - pull Docker images from ECR; - reference sensitive data in Secrets Manager or SSM Parameter Store. - **[ECS task role](/docs/glossary#term-ecs-task-role)**: - gives **each task its own permissions**, for the application inside it; - lets you use **different roles for different ECS services**; - is defined in the **task definition**. AWS's documentation also separates a **task execution role**, used by ECS and Fargate to pull images, write logs and fetch secrets for the task. On Fargate there's no instance profile, so the execution role does that job. ## Load balancer integration [#load-balancer-integration]
![ECS behind an Application Load Balancer: users reach one listener on the ALB, which sends requests to the ECS tasks in the cluster, each registered on its own dynamic host port](/diagrams/containers-ecs-alb.light.svg) ![ECS behind an Application Load Balancer: users reach one listener on the ALB, which sends requests to the ECS tasks in the cluster, each registered on its own dynamic host port](/diagrams/containers-ecs-alb.dark.svg)
One ALB in front of many tasks.
- **[Application Load Balancer](/docs/scaling/alb)**: supported and works for most use cases. With **dynamic host port mapping**, several tasks of the same service can run on one EC2 instance, each on its own port, and the ALB finds them all. Path-based rules let several services share one ALB. - **[Network Load Balancer](/docs/scaling/nlb)**: recommended only for **high throughput / high performance** use cases, or to pair with **AWS PrivateLink**. - **Classic Load Balancer**: works, but not recommended (no advanced features, no Fargate). ## Data volumes [#data-volumes]
![Shared data volumes for ECS tasks: tasks on EC2, Fargate and ECS Managed Instances can mount an Amazon EFS file system shared across Availability Zones, or Amazon S3 Files, which exposes an S3 bucket as a file system](/diagrams/containers-ecs-volumes.light.svg) ![Shared data volumes for ECS tasks: tasks on EC2, Fargate and ECS Managed Instances can mount an Amazon EFS file system shared across Availability Zones, or Amazon S3 Files, which exposes an S3 bucket as a file system](/diagrams/containers-ecs-volumes.dark.svg)
Persistent storage that every task can share.
Containers lose their local files when they stop. For persistent, shared data: - **[Amazon EFS](/docs/storage/efs):** - mount EFS file systems onto ECS tasks; - works with the **EC2** and **Fargate** launch types (and Managed Instances); - tasks running in **any AZ share the same data**; - **Fargate + EFS = serverless**; - **use case:** persistent multi-AZ shared storage for your containers. - **Amazon S3 Files:** - mount an S3 bucket exposed as a **file system** onto ECS tasks; - changes **sync automatically** to the S3 bucket; - **use case:** containers that need file access to data that already lives in S3. The slides say S3 Files works with Fargate and ECS Managed Instances but **not the EC2 launch type**. The AWS documentation now lists the EC2 launch type as **fully supported** too. ## Real-world examples [#real-world-examples] - **A media start-up** runs its API as an ECS service on Fargate behind an ALB: no servers to patch, and it scales by adding tasks. - **A machine learning team** runs inference containers on ECS Managed Instances to use GPU instance types without managing the hosts. - **A CMS** runs several WordPress tasks across AZs, all sharing uploads on EFS. ## Exam tips [#exam-tips] - **"Run containers without managing servers"** → ECS on Fargate. - **"Need specific instance types, custom AMIs, or full control of hosts"** → EC2 launch type (or Managed Instances for specific types without host management). - **"Give one container access to S3 and another to DynamoDB"** → separate ECS task roles. - **"ECS tasks need to pull images from ECR and write logs"** → instance profile (EC2) or task execution role. - **"Several tasks on one instance behind a load balancer"** → ALB with dynamic host port mapping. - **"Persistent storage shared by Fargate tasks across AZs"** → EFS. ## Common traps [#common-traps] - **"Put the app's S3 permissions on the EC2 instance profile."** Use task roles, so each task gets only what it needs. - **"Fargate tasks can use EBS-style local persistent disks across restarts."** Use EFS (or S3 Files) for persistent data. - **"NLB is the default for ECS web apps."** ALB is; NLB is for high throughput or PrivateLink. ## Hands-on lab: a Fargate task [#hands-on-lab-a-fargate-task] **Goal:** run a public container image as an ECS task on Fargate and open it in a browser. A task with 0.25 vCPU and 0.5 GB on Fargate costs about **$0.01 an hour**, plus $0.005 an hour for its public IP. Stop it within the hour. Any Region works. ### Create a cluster [#create-a-cluster] **ECS → Clusters → Create cluster**. Name `saa-cluster`, infrastructure **AWS Fargate (serverless)** only. Create. ### Create a task definition [#create-a-task-definition] **Task definitions → Create new task definition**. Family `saa-web`, launch type **AWS Fargate**, CPU 0.25 vCPU, memory 0.5 GB. Container: name `web`, image `public.ecr.aws/nginx/nginx:latest`, port 80. Create. ### Run the task [#run-the-task] In `saa-cluster` → **Tasks → Run new task**. Launch type Fargate, task definition `saa-web`. Under **Networking**, use the default VPC, a public subnet, **Public IP: turned on**, and a security group allowing HTTP (80) from anywhere. Create. ### Open it [#open-it] When the task is *Running*, open it and copy its **Public IP**. Browse to `http://`: the nginx welcome page. No EC2 instance was ever created. **Expected result:** a container running serverless, reachable from the internet. **Clean up:** stop the task, delete the cluster, deregister the task definition revision, and delete the security group if you created one. ## AWS documentation [#aws-documentation] - [What is Amazon ECS?](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) - [Amazon ECS Managed Instances](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ManagedInstances.html) - [AWS Fargate for Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html) - [Amazon ECS task IAM role](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html) - [Amazon ECS task execution IAM role](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html) - [Use load balancing to distribute ECS service traffic](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-load-balancing.html) - [Use Amazon EFS volumes with Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/efs-volumes.html) - [Configuring S3 Files for Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/s3files-volumes.html) # Amazon EKS (/docs/containers/eks) ## What it is [#what-it-is] **[Amazon EKS](/docs/glossary#term-amazon-eks)** (Elastic Kubernetes Service) launches **managed Kubernetes clusters** on AWS. - **[Kubernetes](/docs/glossary#term-kubernetes)** is an **open-source** system for the automatic deployment, scaling and management of containerized (usually Docker) applications. - It's an **alternative to ECS**: a similar goal, but a different API. - EKS supports **EC2** worker nodes, or **Fargate** for serverless containers. - **Use case:** a company already uses Kubernetes on premises or in another cloud, and wants to move to AWS while keeping Kubernetes. - **Kubernetes is cloud-agnostic:** it runs on any cloud (Azure, Google Cloud…), so the same tools and manifests work everywhere. - For **multiple Regions**, deploy **one EKS cluster per Region**. - Collect logs and metrics with **CloudWatch Container Insights**. AWS runs the **control plane** (the Kubernetes API servers and their database) across several AZs; you run your workloads as **pods** on the worker capacity. A typical cluster puts worker nodes in **private subnets** in several AZs, with load balancers in public subnets for internet traffic and NAT gateways for outbound access. ## Node types [#node-types]
![Ways to run EKS worker capacity under the AWS-managed control plane: managed node groups of EC2 instances in an Auto Scaling group run by EKS; self-managed nodes on your own EC2 instances using the EKS-optimized AMI; Fargate with no nodes to manage, each pod isolated; and EKS Auto Mode, where AWS runs the nodes, scaling and patching](/diagrams/containers-eks-nodes.light.svg) ![Ways to run EKS worker capacity under the AWS-managed control plane: managed node groups of EC2 instances in an Auto Scaling group run by EKS; self-managed nodes on your own EC2 instances using the EKS-optimized AMI; Fargate with no nodes to manage, each pod isolated; and EKS Auto Mode, where AWS runs the nodes, scaling and patching](/diagrams/containers-eks-nodes.dark.svg)
Four ways to provide the capacity pods run on.
- **Managed node groups:** - EKS **creates and manages the nodes** (EC2 instances) for you; - nodes are part of an **ASG managed by EKS**; - supports **On-Demand** or **Spot** Instances. - **Self-managed nodes:** - nodes **you create** and register to the EKS cluster, managed by an ASG; - you can use a prebuilt AMI: the **Amazon EKS-optimized AMI**; - supports On-Demand or Spot Instances. - **AWS Fargate:** - **no maintenance required; no nodes managed.** - **EKS Auto Mode:** - AWS manages the nodes too: **compute autoscaling**, OS **patching**, pod networking, **load balancer** integration and **storage** drivers; - you look after your application containers. **EKS Auto Mode** is newer than the course slides. It sits between managed node groups and Fargate: EC2-based, but with AWS running the nodes. On the exam, "least operational overhead for Kubernetes" still most often points to **Fargate** or **managed node groups**. ## Data volumes [#data-volumes] - You specify a **StorageClass** manifest on your EKS cluster. - It uses a **Container Storage Interface (CSI)**-compliant driver. - Supported storage includes: - **Amazon EBS**; - **Amazon EFS** (the one that **works with Fargate**); - **Amazon FSx for Lustre**; - **Amazon FSx for NetApp ONTAP**; - also Amazon S3, S3 Files and File Cache. ## Running containers outside AWS Regions [#running-containers-outside-aws-regions]
![Running AWS container tools outside AWS Regions: ECS Anywhere keeps the ECS control plane in AWS and runs tasks on your own servers; EKS Anywhere runs a whole Kubernetes cluster in your data centre; EKS Distro is the Kubernetes distribution that EKS uses, which you run yourself](/diagrams/containers-anywhere.light.svg) ![Running AWS container tools outside AWS Regions: ECS Anywhere keeps the ECS control plane in AWS and runs tasks on your own servers; EKS Anywhere runs a whole Kubernetes cluster in your data centre; EKS Distro is the Kubernetes distribution that EKS uses, which you run yourself](/diagrams/containers-anywhere.dark.svg)
The same tools in your own data centre.
- **[ECS Anywhere](/docs/glossary#term-ecs-anywhere):** run ECS tasks on **your own servers or VMs** (registered as *external instances* through the Systems Manager agent), with the **ECS control plane in AWS**. Manage on-premises and cloud containers the same way. - **EKS Anywhere:** run **whole Kubernetes clusters in your own data centre** (VMware vSphere, bare metal, Nutanix and more), with the control plane and nodes on your hardware. It can even run **disconnected** (air-gapped). - **EKS Distro (EKS-D):** the **open-source Kubernetes distribution** that EKS itself uses, with the same versions and patches. You install and run it yourself, with your own tools; AWS support plans don't cover it. - **EKS Hybrid Nodes** (newer) lets on-premises machines join an EKS cluster whose control plane runs in AWS. ECS Anywhere, EKS Anywhere and EKS Distro are on the exam guide's in-scope list but not in the course slides. This section is written from the AWS documentation. ## Real-world examples [#real-world-examples] - **A retailer** runs Kubernetes in its data centre and on Google Cloud; it moves to EKS with the same Helm charts and manifests. - **A bank** runs managed node groups on Spot for batch jobs and Fargate for small internal services. - **A factory** needs containers next to its machines with no internet link; it runs EKS Anywhere on site. ## Exam tips [#exam-tips] - **"Already using Kubernetes", "migrate Kubernetes workloads", "cloud-agnostic containers"** → EKS. - **"Kubernetes without managing nodes"** → EKS on Fargate (or EKS Auto Mode). - **"Nodes managed by AWS, On-Demand or Spot"** → managed node groups. - **"Persistent storage for EKS pods on Fargate"** → EFS. - **"Manage on-premises containers with the ECS control plane"** → ECS Anywhere. - **"Kubernetes in our own data centre, supported by AWS, even disconnected"** → EKS Anywhere. - **"Same Kubernetes as EKS, self-managed anywhere"** → EKS Distro. ## Common traps [#common-traps] - **"EKS uses the ECS API."** EKS uses the standard Kubernetes API. - **"EBS volumes for Fargate pods."** Fargate pods use EFS. - **"One EKS cluster can span Regions."** Use one cluster per Region. ## Check yourself [#check-yourself] An EKS cluster costs $0.10 an hour for the control plane alone, before any nodes, so instead of a lab: Amazon EKS: it's certified Kubernetes-conformant, so existing manifests and tools work; use managed node groups or Fargate for the workers. ECS Anywhere: register the on-premises servers as external instances; the ECS control plane in AWS schedules tasks on them. ## AWS documentation [#aws-documentation] - [What is Amazon EKS?](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) - [Manage compute resources by using nodes](https://docs.aws.amazon.com/eks/latest/userguide/eks-compute.html) - [Automate cluster infrastructure with EKS Auto Mode](https://docs.aws.amazon.com/eks/latest/userguide/automode.html) - [Simplify node lifecycle with managed node groups](https://docs.aws.amazon.com/eks/latest/userguide/managed-node-groups.html) - [Simplify compute management with AWS Fargate](https://docs.aws.amazon.com/eks/latest/userguide/fargate.html) - [Use application data storage for your cluster](https://docs.aws.amazon.com/eks/latest/userguide/storage.html) - [Deploy Amazon EKS clusters across cloud and on-premises environments](https://docs.aws.amazon.com/eks/latest/userguide/eks-deployment-options.html) - [Amazon ECS Anywhere](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-anywhere.html) # Containers (/docs/containers) ## What it is [#what-it-is] **[Docker](/docs/glossary#term-docker)** is a software platform for deploying applications. Each app is packaged in a **[container](/docs/glossary#term-container)**: the app plus everything it needs (libraries, runtime, settings), so it **runs the same everywhere**: - on any machine; - with no compatibility issues; - with predictable behaviour; - with less work, and easier maintenance and deployment; - with any language, any OS, any technology. **Use cases:** microservices architectures, and lift-and-shift of apps from on premises to AWS. One server (for example an EC2 instance) can run many containers at once: a Java app, a Node.js app and a MySQL database side by side. ## Containers vs virtual machines [#containers-vs-virtual-machines]
![Virtual machines versus containers: each virtual machine runs its own guest operating system on a hypervisor, so a host fits few of them; containers share the host operating system through the Docker daemon, so many containers fit on one host](/diagrams/containers-docker-vs-vm.light.svg) ![Virtual machines versus containers: each virtual machine runs its own guest operating system on a hypervisor, so a host fits few of them; containers share the host operating system through the Docker daemon, so many containers fit on one host](/diagrams/containers-docker-vs-vm.dark.svg)
VMs each carry an OS; containers share one.
Docker is *sort of* a virtualization technology, but not exactly: - A **virtual machine** has its own full guest operating system, running on a hypervisor. - **Containers** share the host's operating system through the Docker daemon. They're much lighter, so **many containers fit on one server** and they start in seconds. ## From code to running container [#from-code-to-running-container]
![From code to container: a Dockerfile is built into an image holding the app and its dependencies; the image is pushed to a registry such as Amazon ECR or Docker Hub; a host pulls it and runs it as a container](/diagrams/containers-docker-flow.light.svg) ![From code to container: a Dockerfile is built into an image holding the app and its dependencies; the image is pushed to a registry such as Amazon ECR or Docker Hub; a host pulls it and runs it as a container](/diagrams/containers-docker-flow.dark.svg)
Build an image, store it, run it anywhere.
1. A **Dockerfile** describes how to build the image (for example: start from Ubuntu, copy the app, install it, set the start command). 2. **Build** it into an **image**. 3. **Push** the image to a **repository**: - **Docker Hub** (hub.docker.com): public, with base images for many technologies and operating systems (Ubuntu, MySQL…); - **Amazon ECR**: private repositories, plus public ones in the **ECR Public Gallery** (gallery.ecr.aws). 4. **Pull** and **run** the image as a container on any host. ## Container services on AWS [#container-services-on-aws]
![The AWS container services: Amazon ECS, AWS's own container platform; Amazon EKS, managed open-source Kubernetes; AWS Fargate, serverless compute for both ECS and EKS; and Amazon ECR, which stores container images](/diagrams/containers-services.light.svg) ![The AWS container services: Amazon ECS, AWS's own container platform; Amazon EKS, managed open-source Kubernetes; AWS Fargate, serverless compute for both ECS and EKS; and Amazon ECR, which stores container images](/diagrams/containers-services.dark.svg)
Four services to know.
- **Amazon ECS** (Elastic Container Service): AWS's own container platform. - **Amazon EKS** (Elastic Kubernetes Service): AWS's managed **Kubernetes** (open source). - **AWS Fargate**: AWS's **serverless** container compute; works with both ECS and EKS. - **Amazon ECR** (Elastic Container Registry): stores container images. ## In this group [#in-this-group] ## Exam tips [#exam-tips] - **"Run Docker containers on AWS"** → ECS (or EKS if they already use Kubernetes). - **"Containers with no servers to manage"** → Fargate. - **"Already using Kubernetes", "cloud-agnostic"** → EKS. - **"Store Docker images privately"** → ECR. ## Common traps [#common-traps] - **"Containers each need their own OS, like VMs."** They share the host's OS kernel. - **"Fargate is a separate container orchestrator."** It's the serverless compute under ECS or EKS. ## AWS documentation [#aws-documentation] - [What is Amazon ECS?](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) - [What is Amazon EKS?](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) - [What is Amazon ECR?](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) # Budgets, Cost and Usage Report and cost allocation tags (/docs/cost/budgets-cur-tags) AWS Budgets, the Cost and Usage Report and cost allocation tags are on the exam guide's list but not in the course slides. This page is written from the AWS documentation. ## AWS Budgets [#aws-budgets]
![AWS Budgets: a monthly cost budget of 1,000 dollars alerts when actual or forecasted spend crosses a threshold such as 80 percent; it notifies by email or SNS, and budget actions can apply an IAM policy or SCP to block new resources or stop chosen EC2 or RDS instances](/diagrams/cost-budgets.light.svg) ![AWS Budgets: a monthly cost budget of 1,000 dollars alerts when actual or forecasted spend crosses a threshold such as 80 percent; it notifies by email or SNS, and budget actions can apply an IAM policy or SCP to block new resources or stop chosen EC2 or RDS instances](/diagrams/cost-budgets.dark.svg)
Set a limit, get warned, act automatically.
**[AWS Budgets](/docs/glossary#term-aws-budgets)** lets you set **custom budgets** and be **alerted** when you exceed them, or are **forecasted** to. - **Budget types:** - **cost budgets:** how much you spend; - **usage budgets:** how much of a service you use (hours, GB…); - **RI and Savings Plans utilization** budgets: are your commitments being used? - **RI and Savings Plans coverage** budgets: how much of your usage they cover. - Periods: daily, monthly, quarterly, yearly, or a custom date range; fixed or growing amounts. - **Alerts** on **actual** or **forecasted** spend, by **email** or **SNS** (and chat through Amazon Q Developer in chat apps). - **Budget actions:** when a threshold is reached, automatically (or after your approval): - apply an **IAM policy** or an **SCP** (for example, deny launching new instances); - **stop** chosen **EC2 or RDS** instances. - Filter by service, account, tag, Region… - **Pricing:** monitoring budgets is **free**; the first 2 budgets with actions are free, then $0.10 a day each. ## Cost and Usage Report [#cost-and-usage-report]
![The Cost and Usage Report: CUR 2.0 delivers every cost line item daily to an S3 bucket as Parquet or CSV, where Athena queries it with SQL and QuickSight builds dashboards](/diagrams/cost-cur.light.svg) ![The Cost and Usage Report: CUR 2.0 delivers every cost line item daily to an S3 bucket as Parquet or CSV, where Athena queries it with SQL and QuickSight builds dashboards](/diagrams/cost-cur.dark.svg)
Every line of your bill, ready for SQL.
The **[AWS Cost and Usage Report](/docs/glossary#term-aws-cost-and-usage-report)** (CUR) contains the **most comprehensive set of cost and usage data** available. - Delivered to an **S3 bucket** you own, updated at least once a day. - Breaks costs down **by the hour, day or month**, by **product and resource**, and by **tags** you define. - Integrates with **Athena**, **Redshift** and **QuickSight** for analysis. - Today it's created through **Data Exports**, where **CUR 2.0** is the recommended format (Parquet or CSV), alongside FOCUS-format exports and Cost Optimization Hub recommendations. ## Cost allocation tags [#cost-allocation-tags] - **[Cost allocation tags](/docs/glossary#term-cost-allocation-tag)** let you see costs **by tag** (team, project, environment) in Cost Explorer and the CUR. - **Two types:** - **AWS-generated tags:** created by AWS, with the `aws:` prefix (for example `aws:createdBy`); - **user-defined tags:** your own tags (shown with the `user:` prefix in reports). - **You must activate them** in the **Billing and Cost Management console** (in the management account) before they appear in reports. They only apply to costs **after** activation. - **Cost categories** group costs with rules (for example, accounts 1–3 and tag `team=web` → "Web team"). - A **tag policy** in AWS Organizations helps keep tags consistent across accounts. ## Real-world examples [#real-world-examples] - **A start-up** sets a $500 monthly budget with an alert at 80% forecasted, and a budget action that applies an SCP denying new EC2 launches in the sandbox account at 100%. - **A company** tags every resource with `cost-center`, activates the tag, and queries the CUR with Athena each month to charge each department. ## Exam tips [#exam-tips] - **"Alert when cost exceeds or is forecast to exceed X"** → AWS Budgets. - **"Automatically stop instances or block launches when the budget is exceeded"** → budget actions. - **"Track if Reserved Instances or Savings Plans are being used"** → RI/SP utilization budgets. - **"Most granular billing data, hourly, per resource, query with Athena"** → Cost and Usage Report. - **"Costs per department or project"** → cost allocation tags (activated) or cost categories. ## Common traps [#common-traps] - **"Tags appear in billing as soon as you add them."** You must activate them as cost allocation tags first. - **"Budgets stop spending by themselves."** Only if you configure budget actions; otherwise they just alert. ## Check yourself [#check-yourself] Activate `Project` as a user-defined cost allocation tag in the Billing and Cost Management console of the management account; costs from then on can be grouped by it. An AWS Budgets cost budget of $200 with a budget action that applies an SCP (or IAM policy) denying resource creation when the threshold is reached. ## AWS documentation [#aws-documentation] - [Managing your costs with AWS Budgets](https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-managing-costs.html) - [Configuring budget actions](https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-controls.html) - [What are AWS Cost and Usage Reports?](https://docs.aws.amazon.com/cur/latest/userguide/what-is-cur.html) - [What is AWS Data Exports?](https://docs.aws.amazon.com/cur/latest/userguide/what-is-data-exports.html) - [Using AWS cost allocation tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) - [Organizing costs using AWS Cost Categories](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/manage-cost-categories.html) # Cost Explorer and Cost Anomaly Detection (/docs/cost/cost-explorer-anomaly) ## AWS Cost Explorer [#aws-cost-explorer] **[AWS Cost Explorer](/docs/glossary#term-aws-cost-explorer)** lets you **visualize, understand and manage** your AWS costs and usage over time. - Create **custom reports** that analyze cost and usage data. - Analyze your data at a **high level**: total costs and usage **across all accounts**. - Or at a **monthly, hourly or resource level** granularity. - Group and filter by service, linked account, Region, instance type, usage type, **tag**… - Choose an optimal **Savings Plan** (to lower prices on your bill): Cost Explorer recommends a commitment from your past usage, an alternative to Reserved Instances. - **Forecast usage up to 18 months** based on previous usage (with an 80% prediction interval). - Shows up to **13 months** of history; **rightsizing recommendations** for EC2. - The console is **free**; the Cost Explorer API costs $0.01 per request. For example, the monthly cost by service view might show that EC2 `t2.micro` instances cost $480 a month and `c4.2xlarge` $296, and the Savings Plans page might recommend a $2.40/hour Compute Savings Plan saving about 40%. ## AWS Cost Anomaly Detection [#aws-cost-anomaly-detection]
![AWS Cost Anomaly Detection: a cost monitor watches spend by service, linked account, cost allocation tag or cost category; a machine learning model learns your usual pattern and flags anomalies, alerting by email or SNS with a root-cause analysis; there are no thresholds to set, and you choose individual alerts or a daily or weekly summary](/diagrams/cost-anomaly.light.svg) ![AWS Cost Anomaly Detection: a cost monitor watches spend by service, linked account, cost allocation tag or cost category; a machine learning model learns your usual pattern and flags anomalies, alerting by email or SNS with a root-cause analysis; there are no thresholds to set, and you choose individual alerts or a daily or weekly summary](/diagrams/cost-anomaly.dark.svg)
Machine learning watches your bill.
**[AWS Cost Anomaly Detection](/docs/glossary#term-aws-cost-anomaly-detection)**: - **continuously monitors your cost and usage using ML** to detect unusual spends; - learns your unique, historic spend patterns to detect **one-time cost spikes** and/or **continuous cost increases** (you **don't need to define thresholds**); - monitors **AWS services, member accounts, cost allocation tags or cost categories** (AWS managed monitors automatically include new accounts and tags); - sends you the anomaly detection report with **root-cause analysis**; - notifies you with **individual alerts** or a **daily/weekly summary** (using **SNS** or email). ## Real-world examples [#real-world-examples] - **A developer** leaves a fleet of GPU instances running after a test. Cost Anomaly Detection alerts the next morning with "EC2, us-west-2, account dev-ml" as the root cause, before the month's bill arrives. - **A finance team** uses Cost Explorer's forecast to plan next year's budget, and buys the Savings Plan it recommends. ## Exam tips [#exam-tips] - **"Visualize costs, group by service or tag, forecast"** → Cost Explorer. - **"Recommend a Savings Plan or Reserved Instances"** → Cost Explorer recommendations. - **"Detect unusual spending automatically, no thresholds"** → Cost Anomaly Detection. ## Common traps [#common-traps] - **"Cost Explorer sends alerts at a threshold."** That's AWS Budgets. - **"Anomaly Detection needs a budget amount."** It learns the pattern itself. ## Hands-on lab: look at your costs [#hands-on-lab-look-at-your-costs] **Goal:** explore your own costs and set up anomaly detection. The Cost Explorer console and Cost Anomaly Detection are free. Don't use the Cost Explorer API in a loop: each call costs $0.01. Use the management account (or an account with billing access). ### Explore [#explore] **Billing and Cost Management → Cost Explorer**. Group by **Service** for the last 6 months, then switch to **Daily** and group by **Region**. ### Create a monitor [#create-a-monitor] **Cost Anomaly Detection → Create monitor**: **AWS services**, alert subscription with your email, **daily summary**. **Expected result:** a chart of your spend by service, and a monitor that will email you if spend looks unusual. **Clean up:** delete the monitor if you don't want the emails (it's free to keep). ## AWS documentation [#aws-documentation] - [Analyzing your costs with AWS Cost Explorer](https://docs.aws.amazon.com/cost-management/latest/userguide/ce-what-is.html) - [Forecasting with Cost Explorer](https://docs.aws.amazon.com/cost-management/latest/userguide/ce-forecast.html) - [Getting started with AWS Cost Anomaly Detection](https://docs.aws.amazon.com/cost-management/latest/userguide/getting-started-ad.html) # Cost Management (/docs/cost) The slides cover Cost Explorer, Cost Anomaly Detection and Instance Scheduler. The exam guide also lists **AWS Budgets**, the **Cost and Usage Report** and **Savings Plans**, and asks about cost allocation tags. Those parts are written from the AWS documentation. ## How AWS billing works [#how-aws-billing-works] - You **pay as you go**, per second, hour, GB or request, depending on the service. There's no upfront cost unless you choose a commitment (Savings Plans, Reserved Instances). - With **AWS Organizations**, **[consolidated billing](/docs/identity/organizations-scps#consolidated-billing)** gives **one bill** for all accounts, paid by the management account, and **shares volume discounts, Reserved Instance and Savings Plans discounts** across accounts. - **Data transfer** is a big, often forgotten cost: in is free, out and across AZs or Regions is not (see [networking costs](/docs/vpc/networking-costs)). - The **cost optimization pillar** of the [Well-Architected Framework](/docs/architecture/well-architected): pay only for what you need, measure, and use the right pricing model. ## The tools, by job [#the-tools-by-job]
![AWS cost management tools by job: organize with consolidated billing and cost allocation tags; analyze with Cost Explorer and the Cost and Usage Report; control with AWS Budgets and Cost Anomaly Detection; save with Savings Plans and Reserved Instances, and Instance Scheduler to stop idle servers](/diagrams/cost-tools.light.svg) ![AWS cost management tools by job: organize with consolidated billing and cost allocation tags; analyze with Cost Explorer and the Cost and Usage Report; control with AWS Budgets and Cost Anomaly Detection; save with Savings Plans and Reserved Instances, and Instance Scheduler to stop idle servers](/diagrams/cost-tools.dark.svg)
Organize, analyze, control, save.
- **Organize:** consolidated billing; **[cost allocation tags](/docs/cost/budgets-cur-tags#cost-allocation-tags)** and cost categories to see who spends what. - **Analyze:** **[Cost Explorer](/docs/cost/cost-explorer-anomaly)** for charts, forecasts and recommendations; the **[Cost and Usage Report](/docs/cost/budgets-cur-tags#cost-and-usage-report)** for every line item. - **Control:** **[AWS Budgets](/docs/cost/budgets-cur-tags#aws-budgets)** for thresholds, alerts and actions; **[Cost Anomaly Detection](/docs/cost/cost-explorer-anomaly#aws-cost-anomaly-detection)** for unexpected spend. - **Save:** **[Savings Plans and Reserved Instances](/docs/compute/purchasing-options#savings-plans)**, Spot, rightsizing ([Compute Optimizer](/docs/compute/compute-optimizer)), and **[Instance Scheduler](/docs/cost/instance-scheduler)** to stop servers out of hours. ## In this group [#in-this-group] ## Exam tips [#exam-tips] - **"Alert when spend goes over a threshold"** → AWS Budgets. **"Unexpected, unusual spend without setting thresholds"** → Cost Anomaly Detection. - **"Visualize and forecast costs", "Savings Plans recommendations"** → Cost Explorer. - **"Most detailed billing data, query with Athena"** → Cost and Usage Report. - **"Costs per team or project"** → cost allocation tags (activated in Billing). - **"One bill and shared discounts across accounts"** → consolidated billing. ## AWS documentation [#aws-documentation] - [What is AWS Billing and Cost Management?](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-what-is.html) - [Consolidated billing for AWS Organizations](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/consolidated-billing.html) # Instance Scheduler on AWS (/docs/cost/instance-scheduler) ## What it is [#what-it-is]
![Instance Scheduler on AWS: an EventBridge rule runs a Lambda function every few minutes, which reads schedules such as 9am to 6pm from DynamoDB and starts or stops EC2 and RDS instances whose Schedule tag matches, saving up to 70 percent](/diagrams/cost-instance-scheduler.light.svg) ![Instance Scheduler on AWS: an EventBridge rule runs a Lambda function every few minutes, which reads schedules such as 9am to 6pm from DynamoDB and starts or stops EC2 and RDS instances whose Schedule tag matches, saving up to 70 percent](/diagrams/cost-instance-scheduler.dark.svg)
Servers that clock off when you do.
**[Instance Scheduler on AWS](/docs/glossary#term-instance-scheduler-on-aws)** is an **AWS Solution** deployed through **CloudFormation** (not a service). - **Automatically start and stop your AWS services to reduce costs** (up to **70%**: from 168 running hours a week to 50). - **Example:** stop the company's EC2 instances outside business hours. - Supports **EC2 instances**, **EC2 Auto Scaling groups** and **RDS instances**. - Schedules are managed in a **DynamoDB** table. - Uses resources' **tags** and **Lambda** to stop and start instances. - Supports **cross-account** and **cross-Region** resources. - Can hibernate EC2 instances instead of stopping them, and work with Systems Manager maintenance windows. - You pay only for the resources it uses (Lambda, DynamoDB, CloudWatch), roughly $13 a month. ## Real-world examples [#real-world-examples] - **A company** tags 120 development and test instances `Schedule=uk-office-hours`; they run 8am–7pm on weekdays only, cutting their bill by about two-thirds. ## Exam tips [#exam-tips] - **"Stop development instances outside business hours automatically, lowest effort"** → Instance Scheduler on AWS. - **"Start and stop RDS on a schedule"** → Instance Scheduler (or EventBridge + Lambda yourself). ## Common traps [#common-traps] - **"Instance Scheduler is an AWS service in the console."** It's a solution you deploy with CloudFormation. ## Check yourself [#check-yourself] Deploy Instance Scheduler on AWS with a cross-account configuration, define a weekday 9–18 schedule, and tag the instances with it. ## AWS documentation [#aws-documentation] - [Instance Scheduler on AWS](https://docs.aws.amazon.com/solutions/latest/instance-scheduler-on-aws/solution-overview.html) - [Instance Scheduler on AWS solution page](https://aws.amazon.com/solutions/implementations/instance-scheduler-on-aws/) # Aurora advanced (/docs/databases/aurora-advanced) ## Aurora Serverless [#aurora-serverless] Provisioned Aurora means you choose an instance class and pay for it every hour. For a database that is busy at some times and idle at others, that wastes money. **[Aurora Serverless](/docs/glossary#term-aurora-serverless)** sizes the database for you. - Capacity is measured in **Aurora capacity units (ACUs)**; each ACU is about 2 GiB of memory with matching CPU and networking. - You set a **minimum and maximum** ACU. Aurora adds or removes capacity in steps as small as **0.5 ACU**, as the load changes, with no interruption. - You can set the minimum to **0 ACUs**: when there are no connections for a while, the instance **pauses** and you pay nothing for compute until the next connection resumes it. - You pay **per second** for the ACUs used, plus storage. - Serverless and provisioned instances can be mixed in one cluster. It suits **infrequent, intermittent or unpredictable workloads**, and removes capacity planning. The slides show the first version, where a proxy fleet sat in front of the database. AWS has retired that version. Today's Aurora Serverless (formerly *v2*) scales instances in place, supports replicas, Multi-AZ and Global Database, and can **scale to zero** with automatic pause and resume. ## Cross-Region options [#cross-region-options] ### Aurora cross-Region read replicas [#aurora-cross-region-read-replicas] You can create an Aurora replica cluster in another Region. It's simple to set up and useful for disaster recovery. ### Aurora Global Database [#aurora-global-database]
![Aurora Global Database: applications in the primary Region us-east-1 read and write; storage replication to a secondary cluster in eu-west-1 usually takes under a second; applications there read only; there can be up to 10 secondary Regions, and one can be promoted in about a minute](/diagrams/databases-aurora-global.light.svg) ![Aurora Global Database: applications in the primary Region us-east-1 read and write; storage replication to a secondary cluster in eu-west-1 usually takes under a second; applications there read only; there can be up to 10 secondary Regions, and one can be promoted in about a minute](/diagrams/databases-aurora-global.dark.svg)
One writer Region, read-only copies around the world.
**[Aurora Global Database](/docs/glossary#term-aurora-global-database)** is the recommended way to run Aurora across Regions. 1. **One primary Region** holds the cluster that takes **reads and writes**. 2. Aurora copies data at the storage layer to **up to 10 secondary Regions**, using dedicated infrastructure. **Replication typically takes under a second.** 3. Each secondary cluster can have **up to 16 read replicas**, so users read from a nearby Region with low latency. 4. If the primary Region fails, you **promote** a secondary Region to take writes. The recovery time (RTO) is **under a minute**. 5. **Write forwarding** can let a secondary cluster accept writes and forward them to the primary, so apps in every Region can use a local endpoint. AWS calls a planned move of the writer a **switchover** and an emergency one a **failover**. A **global writer endpoint** always points to the current primary. Older material says up to **5** secondary Regions. The AWS documentation now says **up to 10**. ## Aurora machine learning [#aurora-machine-learning] **Aurora machine learning** lets you call ML models **from SQL**. The database sends data to an ML service and puts the predictions in your query results. - Supported services: **[Amazon SageMaker AI](/docs/ml/sagemaker-personalize#amazon-sagemaker-ai)** (any model you've trained or deployed), **[Amazon Comprehend](/docs/ml/speech-language#amazon-comprehend)** (sentiment analysis) and **Amazon Bedrock** (generative AI foundation models). - You don't need ML experience: a SQL function makes the call. - Use cases: **fraud detection**, **ad targeting**, **sentiment analysis** of reviews, **product recommendations**. For example, an application runs `SELECT` asking for recommended products for a user. Aurora sends the user's profile and history to a SageMaker model and returns "red shirt, blue trousers" as rows. ## Babelfish for Aurora PostgreSQL [#babelfish-for-aurora-postgresql] **[Babelfish](/docs/glossary#term-babelfish)** lets Aurora PostgreSQL understand **Microsoft SQL Server's protocol and its SQL dialect, T-SQL**. - Babelfish adds a second endpoint to the cluster that speaks SQL Server's wire protocol (TDS). - Applications built for SQL Server keep their **SQL Server client driver** and T-SQL code, with **little or no code change**. - After you migrate the database (with **AWS SCT** and **[AWS DMS](/docs/migration/dms-sct)**), the same apps run against Aurora PostgreSQL. You stop paying SQL Server licences. - Applications that use PostgreSQL drivers and PL/pgSQL can use the same database at the same time. ## Real-world examples [#real-world-examples] - **A test environment** is used only in office hours. Aurora Serverless with a minimum of 0 ACUs pauses overnight and at weekends, cutting its compute bill to almost nothing. - **A global game** keeps its primary database in us-east-1 and secondary Regions in Europe and Asia. Players read leaderboards locally; a Region outage is handled by promoting another Region in about a minute. - **A retailer** adds a sentiment score to every product review with one SQL call to Comprehend, without building an ML pipeline. - **A company on SQL Server** moves to Aurora PostgreSQL with Babelfish, keeping its .NET app and T-SQL stored procedures. ## Exam tips [#exam-tips] - **"Unpredictable or intermittent workload", "no capacity planning", "pay per second"** → Aurora Serverless. - **"Global application, low-latency reads in several Regions, Region-level DR with RPO of about a second and RTO under a minute"** → Aurora Global Database. - **"ML predictions from SQL", "SageMaker or Comprehend from the database"** → Aurora machine learning. - **"Run SQL Server applications on Aurora with few code changes"** → Babelfish for Aurora PostgreSQL. ## Common traps [#common-traps] - **"Global Database secondaries accept writes like the primary."** Only the primary writes (write forwarding just passes writes on to it). - **"Babelfish works with Aurora MySQL."** It's for Aurora PostgreSQL only. - **"Aurora Serverless can't scale to zero."** It can now, with a minimum of 0 ACUs. ## Check yourself [#check-yourself] A Global Database lab needs clusters in two Regions for long enough to replicate, which costs dollars rather than cents. Instead: Aurora Serverless: set a minimum (or 0 ACUs with auto-pause) and a maximum; it scales up for the morning burst and down afterwards, billed per second. Aurora Global Database with secondary Regions in Europe and Asia: local, low-latency reads, under a second of replication lag, and promotion of a secondary Region in about a minute. ## AWS documentation [#aws-documentation] - [Using Aurora Serverless](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2.html) - [Scaling to zero ACUs with automatic pause and resume](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2-auto-pause.html) - [Using Amazon Aurora Global Database](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-global-database.html) - [Using Amazon Aurora machine learning](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-ml.html) - [Using Babelfish for Aurora PostgreSQL](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/babelfish.html) # Amazon Aurora (/docs/databases/aurora) ## What it is [#what-it-is] **[Amazon Aurora](/docs/glossary#term-amazon-aurora)** is a relational database engine built by AWS for the cloud. It is **compatible with MySQL and PostgreSQL**: your existing drivers and SQL work as if Aurora were MySQL or PostgreSQL. It isn't open source. Aurora keeps the database engine but rebuilds the storage underneath it. Compute (the DB instances) and storage (one shared cluster volume) are separate, which gives: - **more performance:** AWS claims up to 5× MySQL and 3× PostgreSQL on RDS; - **storage that grows by itself**, up to 128 TiB, or **256 TiB** on newer engine versions, and you pay only for what you use; - **up to 15 replicas** with very little lag (usually under 100 ms); - **near-instant failover**, typically under 30 seconds. It costs about 20% more per instance than RDS, but often does more work per dollar. ## How it works [#how-it-works]
![An Aurora cluster: one writer and up to 15 replicas in different Availability Zones share one cluster volume that keeps six copies of the data, two in each of three AZs; a write needs four of the six copies and a read needs three](/diagrams/databases-aurora-cluster.light.svg) ![An Aurora cluster: one writer and up to 15 replicas in different Availability Zones share one cluster volume that keeps six copies of the data, two in each of three AZs; a write needs four of the six copies and a read needs three](/diagrams/databases-aurora-cluster.dark.svg)
One shared volume, six copies, three AZs.
An **Aurora DB cluster** has: - **One writer** (primary) instance that takes all writes. - **Up to 15 Aurora Replicas** that serve reads, in any AZ. - **One cluster volume** shared by all of them. It keeps **six copies** of your data, **two in each of three AZs**. The storage is designed to keep working through failures: - A **write** succeeds when **4 of the 6** copies have it; a **read** needs **3 of 6**. So Aurora keeps writing even if a whole AZ is lost. - Storage is split into small pieces **striped across hundreds of volumes**, and it **repairs itself**: a damaged copy is rebuilt from its peers. - Because the replicas read the same volume as the writer, there is no copying of data to each replica, which is why replica lag is so low. If the writer fails, Aurora **promotes a replica** to be the new writer automatically, usually in under 30 seconds. Aurora also supports **cross-Region replication** (see [Global Database](/docs/databases/aurora-advanced#aurora-global-database)). ## Endpoints [#endpoints]
![Aurora endpoints: the writer endpoint always points to the writer; the reader endpoint balances connections across the replicas; a custom endpoint points to a set of instances you choose, such as a larger replica for analytics; all instances share one cluster volume](/diagrams/databases-aurora-endpoints.light.svg) ![Aurora endpoints: the writer endpoint always points to the writer; the reader endpoint balances connections across the replicas; a custom endpoint points to a set of instances you choose, such as a larger replica for analytics; all instances share one cluster volume](/diagrams/databases-aurora-endpoints.dark.svg)
Connect to a role, not to one instance.
Instances come and go (failover, auto scaling), so applications connect to **endpoints**, DNS names that follow the right instances: - **Cluster (writer) endpoint:** always points to the current writer. Use it for writes. After a failover it points to the new writer, with no app change. - **[Reader endpoint](/docs/glossary#term-reader-endpoint):** balances **connections** across all the replicas. Use it for read-only queries. - **Custom endpoints:** a set of instances you choose. For example, run analytics queries on two bigger replicas so they don't slow the replicas serving the website. Once you define custom endpoints, you usually stop using the general reader endpoint. - **Instance endpoints:** one specific instance, for troubleshooting. The reader endpoint balances at the connection level, not per query. ## Replica auto scaling [#replica-auto-scaling] **Aurora Replica auto scaling** adds or removes replicas to keep a metric near a target, using Application Auto Scaling. For example: keep average replica **CPU at 60%**, or a target number of connections. When many reads arrive, CPU rises, Aurora adds replicas, and the reader endpoint starts sending connections to them. ## More features [#more-features] - **Automatic failover** and **automated backups** with point-in-time recovery (see [backups](/docs/databases/backups-restore-cloning)). - **Isolation and security:** VPC, encryption with KMS, IAM authentication (see [security](/docs/databases/rds-security-proxy)). - **Industry compliance**, **push-button scaling**, **advanced monitoring** and **routine maintenance**, as with RDS. Most patching happens with little or no downtime. - **Backtrack** (Aurora MySQL): rewind the cluster to a point in time **without restoring a backup**, up to 72 hours back. ## Limits and pricing [#limits-and-pricing] - Instances are billed per hour (or as [Aurora Serverless](/docs/databases/aurora-advanced#aurora-serverless) capacity); storage per GB-month of what you use; plus I/O requests, unless you choose the **Aurora I/O-Optimized** configuration, which has no I/O charges and higher instance and storage prices. - 15 replicas per cluster. Cluster volume up to 128 TiB, or 256 TiB on newer versions (Aurora MySQL 3.10 and later, recent Aurora PostgreSQL 15, 16 and 17 versions). The slides give the maximum as 128 TB in one place and 256 TB in another. The AWS documentation says **256 TiB** on newer engine versions and **128 TiB** on older ones. Remember "it grows automatically to a very large size"; the exact number matters less. ## Real-world examples [#real-world-examples] - **A SaaS company** moves from RDS MySQL to Aurora MySQL: the same code runs, failover drops from minutes to seconds, and reporting runs on a custom endpoint. - **A ticketing site** sets replica auto scaling on CPU. When tickets go on sale, Aurora adds replicas in minutes and removes them afterwards. - **A developer runs a bad `DELETE`** on Aurora MySQL. Backtrack rewinds the cluster to five minutes earlier, without a restore. ## Compared with RDS [#compared-with-rds] | | RDS | Aurora | | --- | --- | --- | | Storage | You size it | Grows itself | | Replicas | Own copies | Share storage | | Failover | 1–2 minutes | Under 30 s | ## Exam tips [#exam-tips] - **"MySQL or PostgreSQL compatible, high performance, high availability, minimal management"** → Aurora. - **"Six copies across three AZs", "self-healing storage"** → Aurora. - **"Send read traffic to replicas automatically"** → reader endpoint. **"Analytics on specific bigger replicas"** → custom endpoint. - **"Replicas scale with read load"** → Aurora Replica auto scaling. - **"Undo a mistake quickly without restoring a backup"** → Backtrack (Aurora MySQL). ## Common traps [#common-traps] - **"Aurora supports Oracle or SQL Server."** Only MySQL- and PostgreSQL-compatible (for SQL Server apps, see [Babelfish](/docs/databases/aurora-advanced#babelfish-for-aurora-postgresql)). - **"You must size Aurora storage in advance."** It grows automatically. - **"Point the app at one replica's instance endpoint for reads."** Use the reader or custom endpoint, which survive replica changes. ## Hands-on lab: an Aurora cluster and its endpoints [#hands-on-lab-an-aurora-cluster-and-its-endpoints] **Goal:** create a small Aurora PostgreSQL cluster with a writer and a replica, and see the writer and reader endpoints. Two `db.t4g.medium` instances cost about **$0.15 an hour** in us-east-1, plus a few cents of storage and I/O. Delete the cluster within the hour. Any Region works. ### Create the cluster [#create-the-cluster] **RDS → Create database → Standard create → Aurora (PostgreSQL Compatible)**. Template **Dev/Test**. Cluster identifier `saa-aurora`, master username `postgres`, self-managed password. Instance configuration **Burstable classes**, `db.t4g.medium`. Availability: **Create an Aurora Replica or Reader node in a different AZ**. Connectivity: **Connect to an EC2 compute resource** → `saa-web`. Tag `Project=saa-lab`, create. ### Look at the endpoints [#look-at-the-endpoints] Open `saa-aurora`. On **Connectivity & security** you see a **Writer** endpoint (`saa-aurora.cluster-…`) and a **Reader** endpoint (`saa-aurora.cluster-ro-…`). The two instances below have the roles **Writer instance** and **Reader instance**. ### Fail over [#fail-over] Select the writer instance → **Actions → Failover**. Within about 30 seconds the roles swap. The writer endpoint name hasn't changed, but it now points to the other instance. **Expected result:** a cluster whose endpoints follow the roles, so applications never need to know which instance is the writer. **Clean up:** delete the reader instance, then the writer instance; when you delete the last instance RDS offers to delete the cluster (no final snapshot, don't retain backups). Delete the `rds-ec2-*` and `ec2-rds-*` security groups. ## AWS documentation [#aws-documentation] - [What is Amazon Aurora?](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_AuroraOverview.html) - [Amazon Aurora storage](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.StorageReliability.html) - [Amazon Aurora endpoint connections](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.Endpoints.html) - [Replication with Amazon Aurora](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Replication.html) - [Amazon Aurora Auto Scaling with Aurora Replicas](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Integrating.AutoScaling.html) - [Backtracking an Aurora DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Managing.Backtrack.html) # Backups, restore and cloning (/docs/databases/backups-restore-cloning) ## What it is [#what-it-is] RDS and Aurora protect your data in two ways: **automated backups**, which let you go back to any second in a window of days, and **manual snapshots**, which you keep as long as you like. Aurora adds **cloning**, a fast copy of a whole cluster. The one rule to remember: **a restore always creates a new database.** It never overwrites the existing one. ## RDS automated backups [#rds-automated-backups]
![RDS automated backups: a daily backup of the whole instance, plus transaction logs uploaded every 5 minutes, let you restore to any second in the retention period of 1 to 35 days; a restore always creates a new DB instance](/diagrams/databases-rds-backups.light.svg) ![RDS automated backups: a daily backup of the whole instance, plus transaction logs uploaded every 5 minutes, let you restore to any second in the retention period of 1 to 35 days; a restore always creates a new DB instance](/diagrams/databases-rds-backups.dark.svg)
Daily backups plus logs give you any point in time.
1. Once a day, during the **backup window** you choose, RDS takes a **full backup** of the instance (a storage snapshot). 2. Every **5 minutes**, RDS uploads the database's **transaction logs** to S3. 3. Together they allow **[point-in-time recovery](/docs/glossary#term-point-in-time-recovery)**: restore to any second from the oldest backup up to about **5 minutes ago**. 4. You keep automated backups for **1 to 35 days**. On RDS, setting **0** turns them off (not recommended). Automated backups are deleted with the instance unless you choose to **retain** them. ## Manual DB snapshots [#manual-db-snapshots] - **You** start a snapshot (or a schedule in AWS Backup does). - It's kept **until you delete it**, even after the database is gone. - Use them before risky changes, for long-term retention, and to **copy** a database to another Region or share it with another account. A **stopped** RDS instance still pays for its storage, and RDS starts it again after 7 days. To switch a database off for a long time, take a **snapshot**, delete the instance, and **restore** the snapshot when you need it. ## Aurora backups [#aurora-backups] - **Automated backups** are **continuous and incremental**, kept **1 to 35 days**, and **can't be turned off**. - **Point-in-time recovery** to any second in that window. - **Manual snapshots** work as on RDS: kept until you delete them. - **Backtrack** (Aurora MySQL) rewinds the existing cluster in place, up to 72 hours, without a restore. ## Restore options [#restore-options] - **Restore a backup or snapshot:** creates a **new** RDS instance or Aurora cluster, with a new endpoint. Point your application at it. - **Restore MySQL on RDS from S3:** 1. Back up your on-premises MySQL database (for example with `mysqldump` or XtraBackup). 2. Upload the backup files to **Amazon S3**. 3. Restore them onto a **new RDS for MySQL** instance. - **Restore MySQL into Aurora from S3:** 1. Back up the on-premises database with **Percona XtraBackup** (this physical backup is required). 2. Upload the files to **Amazon S3**. 3. Restore them into a **new Aurora MySQL cluster**. ## Aurora database cloning [#aurora-database-cloning]
![Aurora cloning uses copy-on-write: the clone starts by sharing the source cluster pages, so nothing is copied; only when one side changes a page is a new page written for that side](/diagrams/databases-aurora-clone.light.svg) ![Aurora cloning uses copy-on-write: the clone starts by sharing the source cluster pages, so nothing is copied; only when one side changes a page is a new page written for that side](/diagrams/databases-aurora-clone.dark.svg)
A clone shares data until something changes.
**[Aurora cloning](/docs/glossary#term-aurora-cloning)** creates a new Aurora cluster from an existing one, much **faster than snapshot and restore**. 1. At first the clone **uses the same storage pages** as the source. Nothing is copied, so it's ready in minutes, even for a huge database. 2. When either cluster **changes a page**, Aurora writes a new page for that cluster only. This is the **copy-on-write** protocol. 3. You pay only for the pages that differ, so clones are **cheap**. The classic use: create a **staging** database from **production** to test a change on real data, without touching production. You can make up to 15 copy-on-write clones per source cluster, and clone across accounts with AWS RAM. ## Real-world examples [#real-world-examples] - **A developer drops the wrong table at 14:35.** The team restores the instance to 14:34:59 as a new instance, checks it, and points the app at it. - **A finance company** must keep year-end data for seven years. It takes a manual snapshot each December and copies it to a second Region. - **A team tests a schema migration** on an Aurora clone of production, made in five minutes, then deletes the clone. ## Exam tips [#exam-tips] - **"Restore to a specific time a few minutes ago"** → automated backups with point-in-time recovery (up to 35 days). - **"Keep a backup for years", "after the database is deleted"** → manual snapshot. - **"Move an on-premises MySQL database to Aurora"** → Percona XtraBackup files in S3, restore into Aurora (or AWS DMS). - **"Create a test or staging copy of production quickly and cheaply"** → Aurora cloning. - **"Pause an RDS database for months"** → snapshot, delete, restore later. ## Common traps [#common-traps] - **"Restoring overwrites the existing database."** It always creates a new one. - **"Aurora automated backups can be disabled."** Only RDS allows 0 days; Aurora's minimum is 1 day. - **"Automated backups are kept forever."** At most 35 days; use manual snapshots for longer. - **"A clone copies all the data first."** Copy-on-write shares pages until they change. ## Hands-on lab: point-in-time restore [#hands-on-lab-point-in-time-restore] **Goal:** make a change, then restore the database to the moment before it, and see that a restore makes a new instance. Two `db.t4g.micro` instances for under an hour: about **$0.04**. Any Region works. **Before you start:** create `saa-db` as in the [RDS lab](/docs/databases/rds#hands-on-lab-create-a-small-rds-database), and wait about 10 minutes after it's available so the first backup exists. ### Make a change [#make-a-change] From `saa-web`, create a table, note the time, then delete the table: ```bash psql -h -U postgres -c "create table orders(id int); insert into orders values (1);" date -u sleep 600 psql -h -U postgres -c "drop table orders;" ``` ### Restore to before the mistake [#restore-to-before-the-mistake] Select `saa-db` → **Actions → Restore to point in time**. Choose **Custom date and time** and enter a UTC time between the `date` output and the `drop`. Identifier `saa-db-restored`, `db.t4g.micro`, same VPC and security groups. Restore. ### Check the result [#check-the-result] When `saa-db-restored` is available, its endpoint is new. Run `select * from orders;` against it: the table and its row are back. The original `saa-db` still has no table. **Expected result:** a second database containing the data as it was before the mistake; the original is unchanged. **Clean up:** delete `saa-db-restored` and `saa-db` (no final snapshots, no retained backups), then the `rds-ec2-*` and `ec2-rds-*` security groups. ## AWS documentation [#aws-documentation] - [Introduction to backups (RDS)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html) - [Restoring a DB instance to a specified time](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIT.html) - [Restoring a backup into an RDS for MySQL DB instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/MySQL.Procedural.Importing.html) - [Backing up and restoring an Aurora DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Managing.Backups.html) - [Physical migration from MySQL by using Percona XtraBackup and Amazon S3](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Migrating.ExtMySQL.S3.html) - [Cloning a volume for an Aurora DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Managing.Clone.html) # DocumentDB, Neptune and Keyspaces (/docs/databases/documentdb-neptune-keyspaces) ## Purpose-built NoSQL databases [#purpose-built-nosql-databases] DynamoDB isn't the only NoSQL database on AWS. Three more each copy a popular open-source data model, so existing applications and skills move over easily: - **DocumentDB** for **MongoDB** (documents); - **Neptune** for **graphs**; - **Keyspaces** for **Apache Cassandra** (wide-column tables). ## Amazon DocumentDB [#amazon-documentdb] Aurora is AWS's own implementation of PostgreSQL and MySQL. **[Amazon DocumentDB](/docs/glossary#term-amazon-documentdb)** (with MongoDB compatibility) is the same idea for **MongoDB**. - MongoDB is a NoSQL database that stores, queries and indexes **JSON documents**. Each document can have its own fields and nested data. - With DocumentDB you use the **same MongoDB drivers, code and tools**. - It's deployed like **Aurora**: a **cluster** with a primary and up to **15 replicas**, over a storage volume replicated across **three AZs**. - **Fully managed** and highly available. - Storage **grows automatically in 10 GB steps**, up to 128 TiB (256 TiB on engine version 8.0 and later). - **Elastic clusters** scale out to workloads with **millions of requests per second** and petabytes of data. **Use it for:** content management, product catalogues and user profiles stored as JSON, and any app already written for MongoDB. ## Amazon Neptune [#amazon-neptune]
![A graph stores things (nodes) and how they relate (edges): Ana and Ben are friends; Ana posted trip photos; Ben likes the post and wrote a comment on it](/diagrams/databases-graph.light.svg) ![A graph stores things (nodes) and how they relate (edges): Ana and Ben are friends; Ana posted trip photos; Ben likes the post and wrote a comment on it](/diagrams/databases-graph.dark.svg)
A graph keeps things and the links between them.
**[Amazon Neptune](/docs/glossary#term-amazon-neptune)** is a fully managed **graph database**. A graph stores **nodes** (people, posts, comments) and **edges** (the relationships between them: friends with, posted, likes, wrote). A social network is the classic graph: users have friends, posts have comments, comments have likes from users, users share and like posts. Questions such as "friends of friends who liked this post" take many joins in a relational database but are natural in a graph. - Highly available across **three AZs**, with up to **15 read replicas**. - Built for **highly connected data** and complex queries over it: it stores **billions of relationships** and queries the graph in **milliseconds**. - Query languages: **Gremlin** and **openCypher** (property graphs) and **SPARQL** (RDF graphs). **Use it for:** **knowledge graphs** (like Wikipedia), **fraud detection** (rings of linked accounts and cards), **recommendation engines** and **social networking**. ### Neptune Streams [#neptune-streams] **Neptune Streams** is a real-time, ordered record of **every change** to the graph data. - Changes are available **immediately** after they're written. - **No duplicates** and **strict order**. - You read the stream through an **HTTP REST API**, for example from an application on EC2 or a Lambda function you schedule. - Use cases: - **send notifications** when certain changes happen; - **keep a copy of the graph in another store**, such as S3, OpenSearch or ElastiCache; - **replicate data across Regions** in Neptune. ## Amazon Keyspaces (for Apache Cassandra) [#amazon-keyspaces-for-apache-cassandra] Apache Cassandra is an open-source, distributed NoSQL **wide-column** database, built for huge amounts of data and heavy write traffic. **[Amazon Keyspaces](/docs/glossary#term-amazon-keyspaces)** is a managed, **Cassandra-compatible** service. - **Serverless**, scalable, highly available and fully managed. Tables **scale up and down automatically** with traffic. - Tables are **replicated three times across AZs**. - You use the **Cassandra Query Language (CQL)** and existing Cassandra drivers. - **Single-digit millisecond** latency at any scale, thousands of requests per second and more. - Capacity: **on-demand** or **provisioned with auto scaling**, like DynamoDB. - **Encryption**, **backups**, and **point-in-time recovery up to 35 days**. **Use it for:** storing **IoT device information**, **time-series data**, and moving existing Cassandra workloads off self-managed clusters. ## Real-world examples [#real-world-examples] - **A publisher's CMS** is built on MongoDB. Moving to DocumentDB keeps the code and removes the work of running MongoDB replica sets. - **A bank** loads accounts, cards, devices and transactions into Neptune and looks for unusual rings of shared devices to catch fraud. - **A telecom company** runs a 30-node Cassandra cluster for device events. Keyspaces replaces it, with no servers to patch and capacity that follows the traffic. ## Exam tips [#exam-tips] - **"MongoDB", "JSON documents", "MongoDB compatible"** → DocumentDB. - **"Graph", "relationships", "social network", "knowledge graph", "fraud rings", "recommendations"** → Neptune. - **"Change events from a graph database"** → Neptune Streams. - **"Apache Cassandra", "CQL"** → Keyspaces. - **"Serverless NoSQL with no particular open-source API"** → DynamoDB. ## Common traps [#common-traps] - **"DocumentDB is open-source MongoDB."** It's AWS's own engine that speaks the MongoDB API. - **"Use DynamoDB for deep relationship queries."** Many-hop relationship queries are what Neptune is for. - **"Keyspaces needs you to size Cassandra nodes."** It's serverless; there are no nodes. ## Check yourself [#check-yourself] DocumentDB and Neptune bill for cluster instances by the hour, and they need a client inside the VPC to try them, so instead of a lab: Amazon DocumentDB: it's MongoDB-compatible, so the app keeps its drivers and queries, and AWS runs a cluster with replicas across three AZs. Amazon Neptune: the shared details form a graph, and following the links between claims, people and accounts is a fast graph query. Amazon Keyspaces: Cassandra-compatible, uses CQL, serverless with on-demand or provisioned capacity. ## AWS documentation [#aws-documentation] - [What is Amazon DocumentDB?](https://docs.aws.amazon.com/documentdb/latest/developerguide/what-is.html) - [Amazon DocumentDB quotas and limits](https://docs.aws.amazon.com/documentdb/latest/developerguide/limits.html) - [What is Amazon Neptune?](https://docs.aws.amazon.com/neptune/latest/userguide/intro.html) - [Capturing graph changes with Neptune Streams](https://docs.aws.amazon.com/neptune/latest/userguide/streams.html) - [What is Amazon Keyspaces?](https://docs.aws.amazon.com/keyspaces/latest/devguide/what-is-keyspaces.html) # DynamoDB advanced (/docs/databases/dynamodb-advanced) ## DynamoDB Accelerator (DAX) [#dynamodb-accelerator-dax]
![DAX sits between the application and DynamoDB as an item and query cache with the same API, answering in microseconds; ElastiCache is where the application stores results it computes itself, such as aggregations](/diagrams/databases-dax.light.svg) ![DAX sits between the application and DynamoDB as an item and query cache with the same API, answering in microseconds; ElastiCache is where the application stores results it computes itself, such as aggregations](/diagrams/databases-dax.dark.svg)
DAX caches DynamoDB; ElastiCache caches your own results.
**[DAX](/docs/glossary#term-dax)** is a fully managed, highly available **in-memory cache for DynamoDB**. - It solves **read congestion**: when many requests read the same items ("hot keys"), DAX answers from memory. - **Microsecond** latency for cached data, instead of single-digit milliseconds. - **No application logic changes:** DAX speaks the same API as DynamoDB. You swap the DynamoDB client for the DAX client and point it at the cluster. - It caches **items** (`GetItem`) and **query and scan results** (`Query`, `Scan`). The default **TTL is 5 minutes**. - Writes go **through** DAX to DynamoDB, then into the cache. - A DAX cluster has one or more nodes in your VPC. DAX serves **eventually consistent** reads. A strongly consistent read passes straight through to DynamoDB, so DAX doesn't help apps that need strong consistency. ### DAX vs ElastiCache [#dax-vs-elasticache] - **DAX:** caches DynamoDB **items, queries and scans**, with no code changes. - **ElastiCache:** stores things **your application computes**, such as the result of aggregating many items. Use both together if needed. ## Stream processing [#stream-processing]
![Change streams: item changes in a table go to DynamoDB Streams, kept 24 hours, where a Lambda trigger can react, for example by sending a welcome email through SNS; or to Kinesis Data Streams, kept up to a year, and on through Data Firehose to S3](/diagrams/databases-dynamodb-streams.light.svg) ![Change streams: item changes in a table go to DynamoDB Streams, kept 24 hours, where a Lambda trigger can react, for example by sending a welcome email through SNS; or to Kinesis Data Streams, kept up to a year, and on through Data Firehose to S3](/diagrams/databases-dynamodb-streams.dark.svg)
React to every change in a table.
A stream is an **ordered record of item-level changes** (create, update, delete) in a table. Use cases: - **React in real time**, for example send a welcome email when a new user item appears. - **Real-time usage analytics.** - **Insert into derived tables**, such as a summary table. - **Cross-Region replication** (global tables use this idea). - **Invoke Lambda** on every change. DynamoDB offers two kinds of stream: **[DynamoDB Streams](/docs/glossary#term-dynamodb-streams):** - Records kept for **24 hours**. - A limited number of consumers. - Processed with **Lambda triggers**, or the DynamoDB Streams Kinesis Adapter (with the Kinesis Client Library). - You choose what each record holds: keys only, the new item, the old item, or both. **Kinesis Data Streams for DynamoDB (newer):** - Records kept up to **1 year**. - **Many consumers**. - Processed with **Lambda**, **Managed Service for Apache Flink**, **Data Firehose** (to S3, Redshift, OpenSearch) and **Glue streaming ETL**. See [Kinesis and Data Firehose](/docs/integration/kinesis). ## Global tables [#global-tables]
![DynamoDB global tables: replicas of one table in us-east-1 and ap-southeast-2; applications read and write in both Regions, changes replicate both ways, usually in under a second, and if the same item changes in two Regions the last write wins](/diagrams/databases-global-tables.light.svg) ![DynamoDB global tables: replicas of one table in us-east-1 and ap-southeast-2; applications read and write in both Regions, changes replicate both ways, usually in under a second, and if the same item changes in two Regions the last write wins](/diagrams/databases-global-tables.dark.svg)
One table, writable in every Region.
A **[global table](/docs/glossary#term-global-table)** keeps replicas of a table in several Regions. - **Low latency** for users around the world: each reads and writes the replica in their Region. - **Active-active** (multi-active) replication: apps can **read and write in any Region**. - Changes replicate to the other Regions, **usually within a second**. - If the same item is changed in two Regions at once, the **last writer wins**. Global tables also offer **multi-Region strong consistency (MRSC)**: a write is confirmed only when it's safe in more than one Region, so a strongly consistent read in any Region sees the latest data. It needs exactly three Regions (or two replicas and a "witness"). The default is multi-Region eventual consistency. The slides say you must **enable DynamoDB Streams** before creating a global table. In the current version of global tables, DynamoDB manages replication for you. The new **multi-Region strong consistency** mode is also newer than the slides. ## Time to live (TTL) [#time-to-live-ttl] **[TTL](/docs/glossary#term-time-to-live-ttl)** deletes items automatically after an expiry time. - You choose an attribute (for example `ExpTime`) that holds the expiry as a **Unix epoch timestamp in seconds** (a Number). - A background process finds expired items and **deletes them, typically within a few days** of expiry. Until then they can still appear in reads, so filter them out if it matters. - TTL deletes **don't use write capacity** and cost nothing. - Deletions appear in DynamoDB Streams, so you can archive expired items. Use cases: keep only **current items** to save storage, meet **data-retention rules**, and expire **web sessions**. ## Backups for disaster recovery [#backups-for-disaster-recovery] - **[Point-in-time recovery (PITR)](/docs/glossary#term-point-in-time-recovery):** optional **continuous backups**. Restore the table to **any second** in the recovery window, which is **35 days by default** (you can set 1 to 35). The restore creates a **new table**. - **On-demand backups:** **full backups** kept until you delete them, for long-term retention. They **don't affect performance or latency**. Manage them in **[AWS Backup](/docs/dr/aws-backup)** to copy them to other Regions or accounts. Restoring also creates a **new table**. ## Integration with Amazon S3 [#integration-with-amazon-s3] - **Export to S3** (needs **PITR** on): - from **any point in time** in the PITR window, as a **full** or **incremental** export; - **doesn't use read capacity** or affect the table; - in **DynamoDB JSON** or **Amazon Ion** format; - then query it with **[Athena](/docs/analytics/athena)**, keep snapshots for auditing, or transform it (ETL) and import it back. - **Import from S3:** - from **CSV**, **DynamoDB JSON** or **Ion** files; - **creates a new table** and **doesn't use write capacity**; - import errors are logged in **CloudWatch Logs**. ## Real-world examples [#real-world-examples] - **A product catalogue** gets the same few hundred items read millions of times a day. DAX answers in microseconds and DynamoDB read costs drop. - **A sign-up service** writes a user item; DynamoDB Streams triggers a Lambda function that sends the welcome email. - **A global chat app** uses a global table in three Regions, so every user writes to a nearby Region. - **A session table** sets TTL on each session item, so old sessions delete themselves for free. - **An analytics team** exports a table to S3 every night and queries it with Athena, without touching the live table's capacity. ## Exam tips [#exam-tips] - **"Microsecond reads for DynamoDB", "hot items", "no code changes"** → DAX. - **"Cache aggregation results computed by the app"** → ElastiCache. - **"React to item changes", "trigger Lambda on insert"** → DynamoDB Streams. - **"Keep change records longer than 24 hours", "many consumers"** → Kinesis Data Streams for DynamoDB. - **"Multi-Region, active-active, low latency reads and writes everywhere"** → global tables. - **"Delete old items automatically", "expire sessions"** → TTL. - **"Restore to a point in time in the last 35 days"** → PITR. **"Keep backups for years"** → on-demand backups (AWS Backup for cross-Region copies). - **"Analyse DynamoDB data with SQL without using capacity"** → export to S3, query with Athena. - **"Load a large CSV into a new DynamoDB table cheaply"** → import from S3. ## Common traps [#common-traps] - **"DAX speeds up strongly consistent reads."** Strongly consistent reads pass through to DynamoDB. - **"TTL deletes items the second they expire."** It typically takes up to a few days. - **"Restore a DynamoDB backup over the existing table."** Restores always create a new table. - **"Export to S3 without PITR."** Export needs point-in-time recovery turned on. ## Hands-on lab: expire items with TTL and watch a stream [#hands-on-lab-expire-items-with-ttl-and-watch-a-stream] **Goal:** turn on a stream and TTL for a table, and see a change record appear. A few on-demand requests and stream reads cost **less than a cent**. Any Region works. **Before you start:** create the `saa-games` table from the [DynamoDB lab](/docs/databases/dynamodb#hands-on-lab-a-table-with-a-composite-key). ### Turn on the stream [#turn-on-the-stream] Open `saa-games` → **Exports and streams → DynamoDB stream details → Turn on**, view type **New and old images**. ### Turn on TTL [#turn-on-ttl] **Additional settings → Time to Live (TTL) → Turn on**, attribute name `ExpTime`. Use **Run preview** with the current time to see which items would expire. ### Add an expiring item [#add-an-expiring-item] Get the current epoch time (in CloudShell, `date +%s`), subtract 60, and create an item `u9` / `1` with `ExpTime` set to that Number. The item is already expired; DynamoDB will delete it in the background, typically within a few days. ### See the change record [#see-the-change-record] In CloudShell: ```bash ARN=$(aws dynamodb describe-table --table-name saa-games --query Table.LatestStreamArn --output text) SHARD=$(aws dynamodbstreams describe-stream --stream-arn $ARN --query 'StreamDescription.Shards[0].ShardId' --output text) IT=$(aws dynamodbstreams get-shard-iterator --stream-arn $ARN --shard-id $SHARD --shard-iterator-type TRIM_HORIZON --query ShardIterator --output text) aws dynamodbstreams get-records --shard-iterator $IT ``` You see an `INSERT` record for the item you created, with its new image. **Expected result:** every change to the table shows up as an ordered record in the stream, and expired items are queued for free deletion. **Clean up:** delete the `saa-games` table. Its stream goes with it. ## AWS documentation [#aws-documentation] - [In-memory acceleration with DAX](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.html) - [DAX: how it works](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.concepts.html) - [Change data capture with DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/streamsmain.html) - [Global tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html) - [Time to Live (TTL)](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html) - [Point-in-time recovery](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Point-in-time-recovery.html) - [On-demand backup and restore](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/backuprestore_HowItWorks.html) - [Export to S3](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/S3DataExport.HowItWorks.html) and [import from S3](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/S3DataImport.HowItWorks.html) # Amazon DynamoDB (/docs/databases/dynamodb) ## What it is [#what-it-is] **[Amazon DynamoDB](/docs/glossary#term-amazon-dynamodb)** is a fully managed, **serverless [NoSQL](/docs/glossary#term-nosql) database**. There are no servers or instances to choose: you create a table and start reading and writing. - **Highly available:** data is replicated across **three AZs** in the Region. - **Massive scale:** millions of requests per second, trillions of items, hundreds of TB, with **single-digit millisecond** performance whether you have ten users or a hundred million. - **Not relational:** no joins and no SQL schema, but it does support **transactions**. - **Security** through **IAM**: who can read or write which table (or even which items) is an IAM policy. - **No maintenance or patching**, always available. Low cost, with automatic scaling. AWS built DynamoDB for its own shopping cart: a workload that needs every request to be fast, at any scale. ## Tables, items and keys [#tables-items-and-keys]
![A DynamoDB table of game scores: the primary key is the partition key User_ID plus the sort key Game_ID; Score and Result are attributes, and an item does not need every attribute: the third item has no Result](/diagrams/databases-dynamodb-table.light.svg) ![A DynamoDB table of game scores: the primary key is the partition key User_ID plus the sort key Game_ID; Score and Result are attributes, and an item does not need every attribute: the third item has no Result](/diagrams/databases-dynamodb-table.dark.svg)
A table of game results, keyed by user and game.
- DynamoDB is made of **tables**. Each table holds any number of **items** (like rows). - Each item has **attributes** (like columns). Attributes can be added at any time, and items don't all need the same ones. So you can **change the schema quickly**: new items just carry new attributes. - An item can be at most **400 KB**. - Every table has a **primary key**, chosen **when you create the table**: - **[Partition key](/docs/glossary#term-partition-key)** only: each item has a unique value, such as `User_ID`. DynamoDB hashes it to decide where the item is stored. - **Partition key + [sort key](/docs/glossary#term-sort-key)** (a *composite* key): items with the same partition key are stored together, sorted by the sort key. In the example, one user (`873e0634`) has many games, each identified by `Game_ID`. - Pick a partition key with **many different values** that are used evenly, so the load spreads across the table. **Data types:** - **Scalar:** String, Number, Binary, Boolean, Null. - **Document:** List, Map (nested JSON-like data). - **Set:** String Set, Number Set, Binary Set. ## Capacity modes [#capacity-modes] You choose how DynamoDB handles read and write throughput, per table. You can switch between modes later. ### On-demand mode [#on-demand-mode] - Reads and writes **scale up and down automatically** with your traffic. **No capacity planning.** - You **pay per request** (read request units and write request units). If nothing happens, you pay nothing for throughput. - Great for **unpredictable** workloads, **sudden steep spikes**, and new apps where you don't know the traffic yet. - It costs more per request than well-used provisioned capacity. ### Provisioned mode [#provisioned-mode] - You specify how many reads and writes per second the table supports, in **read capacity units (RCU)** and **write capacity units (WCU)**, and pay for them by the hour whether you use them or not. - You must plan capacity ahead. Add **auto scaling** to raise and lower RCU and WCU to keep usage near a target percentage. - Requests above the capacity are **throttled**. - Cheaper for **steady, predictable** traffic. Roughly: **1 WCU** = one write per second of up to 1 KB; **1 RCU** = one strongly consistent read per second of up to 4 KB, or two eventually consistent reads. The slides say **provisioned** mode is the default. AWS now makes **on-demand the default and recommended** mode for most tables, after cutting on-demand prices. The exam logic is unchanged: unpredictable traffic → on-demand; steady, planned traffic → provisioned with auto scaling. ## Table classes [#table-classes] - **DynamoDB Standard:** the default, for most tables. - **DynamoDB Standard-Infrequent Access (Standard-IA):** cheaper storage, more expensive reads and writes. For tables where **storage is most of the cost**, such as old orders, logs or past game history. ## Real-world examples [#real-world-examples] - **A mobile game** stores each player's profile and game results in DynamoDB, keyed by player ID and game ID. Lookups take a few milliseconds even with millions of players. - **A ticket site** gets almost no traffic, then a million requests in a minute when tickets go on sale. On-demand mode absorbs the spike without planning. - **An IoT company** writes a steady 5,000 readings a second around the clock. Provisioned capacity with auto scaling is the cheapest fit. ## Exam tips [#exam-tips] - **"Serverless NoSQL", "key-value", "single-digit millisecond", "any scale"** → DynamoDB. - **"Schema changes often", "flexible attributes"** → DynamoDB. - **"Unpredictable traffic", "sudden spikes", "no capacity planning"** → on-demand mode. - **"Steady, predictable traffic, lowest cost"** → provisioned mode with auto scaling. - **"Store session data", "shopping cart"** → DynamoDB (with TTL), as an alternative to ElastiCache. - **"Mostly stored, rarely read table, reduce cost"** → Standard-IA table class. - **"Items larger than 400 KB"** → store the object in S3 and its key in DynamoDB. ## Common traps [#common-traps] - **"DynamoDB supports joins and complex SQL queries."** It doesn't; design your keys around how you read the data. - **"Change the primary key later."** The key is fixed at creation; you'd need a new table. - **"Provisioned mode for an unpredictable workload."** It throttles above capacity; on-demand handles spikes. ## Hands-on lab: a table with a composite key [#hands-on-lab-a-table-with-a-composite-key] **Goal:** create a DynamoDB table with a partition key and sort key, add items with different attributes, and query them. An on-demand table that stores a few items costs **less than a cent**: you pay per request and per GB stored. Any Region works. ### Create the table [#create-the-table] **DynamoDB → Tables → Create table**. Name `saa-games`, partition key `User_ID` (String), sort key `Game_ID` (String). Keep **Default settings** (on-demand). Tag `Project=saa-lab`, create. ### Add items [#add-items] Open the table → **Explore table items → Create item**. Add `User_ID = u1`, `Game_ID = 4421`, `Score = 92` (Number), `Result = Win`. Add a second item `u1` / `1894` with only `Score = 14`. Add a third `u2` / `4521` with a new attribute `Level = 7`. No schema change was needed. ### Query by partition key [#query-by-partition-key] Choose **Query**, `User_ID = u1`, run. You get both of `u1`'s games, sorted by `Game_ID`. Try a **Scan** too: it reads every item, which is slow and costly on a big table. **Expected result:** items with different attributes in one table, and a query that returns one user's items in sort-key order. **Clean up:** delete the `saa-games` table (untick creating a backup). ## AWS documentation [#aws-documentation] - [What is Amazon DynamoDB?](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) - [Core components of DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html) - [DynamoDB throughput capacity](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/capacity-mode.html) - [On-demand capacity mode](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/on-demand-capacity-mode.html) - [Provisioned capacity mode](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/provisioned-capacity-mode.html) - [Table classes](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.TableClasses.html) # Amazon ElastiCache (/docs/databases/elasticache) ## What it is [#what-it-is] **[Amazon ElastiCache](/docs/glossary#term-amazon-elasticache)** is to caches what RDS is to relational databases: AWS runs the cache servers, and you use them. A cache is an **in-memory** data store: it keeps data in RAM, so reads take well under a millisecond. ElastiCache supports three engines: - **Valkey**, the open-source fork of Redis that AWS now leads with; - **Redis OSS**; - **Memcached**. What a cache does for you: - **Takes load off the database** for read-heavy workloads: popular data is served from memory. - **Makes the application stateless:** user sessions live in the cache, not on one web server, so any server can handle any request. - AWS handles OS maintenance and patching, setup, monitoring, failure recovery and backups. The catch: **using ElastiCache means changing your application code.** The app must decide what to cache, read from the cache first, and keep it up to date. You can create a **serverless cache**, ready in under a minute with no nodes to size, or a **node-based cluster** where you choose node types such as `cache.m7g.large`. ## Lazy loading: the database cache pattern [#lazy-loading-the-database-cache-pattern]
![Lazy loading: the application reads from ElastiCache first; on a hit it is done; on a miss it reads from the RDS database, then writes the result to the cache for next time](/diagrams/databases-lazy-loading.light.svg) ![Lazy loading: the application reads from ElastiCache first; on a hit it is done; on a miss it reads from the RDS database, then writes the result to the cache for next time](/diagrams/databases-lazy-loading.dark.svg)
Check the cache first; fill it on a miss.
1. The application asks **ElastiCache** for the data. If it's there (a **cache hit**), it's done. 2. If it isn't (a **cache miss**), the application reads from the database, here **RDS**. 3. It then **writes the result to the cache**, so the next request is a hit. The cache needs an **invalidation strategy** so it only holds current data. That's the hard part. There's an old saying: the two hard things in computer science are cache invalidation and naming things. ## Caching strategies [#caching-strategies] - **[Lazy loading](/docs/glossary#term-lazy-loading)** (cache-aside): only requested data is cached, so the cache stays small. But a miss costs three trips (cache, database, cache), and cached data can become **stale** when the database changes. - **[Write-through](/docs/glossary#term-write-through):** whenever the app writes to the database, it also writes to the cache. Cached data is **never stale**, but every write does two writes, and the cache fills with data nobody may read. - **TTL (time to live):** give each cache entry an expiry time, so stale data disappears by itself. Combine TTL with either strategy. - **Session store:** keep temporary session data (who's logged in, the cart) in the cache with a TTL. ## User session store [#user-session-store] 1. A user logs in through any of your application servers. 2. That server **writes the session** into ElastiCache. 3. The user's next request reaches **another server**. 4. That server **reads the session** from ElastiCache, and the user is still logged in. ## Valkey and Redis OSS vs Memcached [#valkey-and-redis-oss-vs-memcached] **Valkey and Redis OSS:** - **Multi-AZ** with **automatic failover**: a replica is promoted if the primary fails. - **Read replicas** to scale reads and for high availability. - **Durability:** data can be persisted (AOF), and you can **back up and restore**. - Rich data types, such as **sets** and **sorted sets**, plus pub/sub and more. - **Cluster mode** splits data across shards. **Memcached:** - **Multiple nodes for partitioning** data (sharding). - **No replication**, so no high availability: a lost node loses its data. - **Not persistent**. (Serverless Memcached caches do support backup and restore.) - **Multithreaded**, and the simplest model. **Rule of thumb:** Valkey or Redis OSS when you need availability, durability, backups or rich data types; Memcached for a simple, multithreaded cache you can afford to lose. ## Cache security [#cache-security] - **IAM authentication** for **Valkey and Redis OSS 7 or later**: the client gets a short-lived token from its IAM identity instead of a password. - Otherwise, **IAM policies** on ElastiCache only control the **AWS API** (who can create or delete a cache), not access to the data. - **Redis AUTH:** a password or token set when you create a Valkey or Redis OSS cache, an extra layer on top of security groups. It's now superseded by **role-based access control (RBAC)**, with users and permissions; serverless caches must use RBAC. - **Encryption in transit** (TLS) and at rest (KMS). - **Memcached** supports **SASL** authentication. - **Security groups** decide which clients can reach the cache, as for any VPC resource. The slides name only Redis and Memcached. ElastiCache now offers **Valkey** (an open-source Redis fork) as a third engine, calls the other one **Redis OSS**, and has a **serverless** option. For the exam, treat Valkey like Redis. ## Use case: a real-time leaderboard [#use-case-a-real-time-leaderboard] Gaming leaderboards are expensive to compute in a relational database. A Valkey or Redis **sorted set** keeps members **unique** and **ordered by score**. Each new score is ranked as it's added, so the top ten is always one fast command away. ## Real-world examples [#real-world-examples] - **A news site's home page** is built from 40 database queries. With lazy loading and a 60-second TTL, the database sees one query per minute instead of thousands. - **A web shop behind a load balancer** keeps user sessions in ElastiCache, so it can drop sticky sessions and scale servers freely. - **A mobile game** keeps its global leaderboard in a Valkey sorted set and updates it in real time. ## Exam tips [#exam-tips] - **"Reduce read load on RDS", "frequently read data", "sub-millisecond reads"** → ElastiCache. - **"Store user sessions so the app is stateless"** → ElastiCache (or DynamoDB). - **"Cache must survive node failure", "Multi-AZ", "backups", "sorted sets"** → Valkey / Redis OSS. - **"Simple cache, multithreaded, data loss is fine"** → Memcached. - **"Data in the cache is stale"** → write-through or a TTL. **"Cache holds data nobody reads"** → lazy loading. - **"Leaderboard"** → Redis/Valkey sorted sets. - **"Least application change for caching DynamoDB"** → DAX, not ElastiCache (see [DynamoDB advanced](/docs/databases/dynamodb-advanced#dynamodb-accelerator-dax)). ## Common traps [#common-traps] - **"ElastiCache needs no code changes."** The app must be written to use the cache. - **"Memcached for high availability."** It has no replication; use Valkey or Redis OSS. - **"IAM policies control who can read cache data."** Only with IAM authentication (Valkey/Redis OSS 7+); otherwise IAM covers the API, and AUTH/RBAC covers the data. ## Hands-on lab: a serverless Valkey cache [#hands-on-lab-a-serverless-valkey-cache] **Goal:** create a serverless cache, connect from EC2, and store a value with an expiry. A serverless Valkey cache costs **a few cents an hour** at most: a minimum storage charge plus tiny request charges. Delete it within the hour. Any Region works. **Before you start:** you need `saa-web` in the default VPC. ### Create the cache [#create-the-cache] **ElastiCache → Valkey caches → Create Valkey cache**. Choose **Serverless**, name `saa-cache`, default settings (default VPC and subnets). Under security groups, choose a group that allows TCP **6379** from `saa-web`'s security group (create one if needed). Tag `Project=saa-lab`, create. ### Connect from EC2 [#connect-from-ec2] Copy the cache **endpoint**. From `saa-web`: ```bash sudo dnf install -y valkey valkey-cli -h --tls -p 6379 ``` (If the `valkey` package isn't available, `sudo dnf install -y redis6` and use `redis6-cli` the same way.) ### Store and expire a value [#store-and-expire-a-value] ```text SET session:42 "user=ana" EX 30 GET session:42 TTL session:42 ``` Run `GET session:42` again after 30 seconds: it returns `(nil)`. The entry expired by itself, which is how a session store cleans up. **Expected result:** a working in-memory cache reached over TLS, and a key that disappears when its TTL runs out. **Clean up:** delete `saa-cache` (no final backup) and the security group you created for it. ## AWS documentation [#aws-documentation] - [What is Amazon ElastiCache?](https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/WhatIs.html) - [Comparing Valkey, Memcached and Redis OSS](https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/SelectEngine.html) - [Caching strategies](https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Strategies.html) - [Authenticating with IAM](https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/auth-iam.html) - [Authenticating with the AUTH command](https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/auth.html) - [Minimizing downtime with Multi-AZ](https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/AutoFailover.html) # Databases (/docs/databases) ## What it is [#what-it-is] A database keeps your application's data and answers questions about it. AWS runs many kinds of database for you as **managed services**: AWS handles the servers, patching, backups and replication, and you work with the data. There's no single best database. Each kind is built for a shape of data and a way of reading it. Choosing well is a big part of the exam, so this page starts with the map. ## Database types [#database-types]
![Database types on AWS: relational (RDS, Aurora), key-value (DynamoDB), in-memory (ElastiCache), document (DocumentDB), graph (Neptune), wide-column (Keyspaces), time series (Timestream) and data warehouse (Redshift)](/diagrams/databases-types.light.svg) ![Database types on AWS: relational (RDS, Aurora), key-value (DynamoDB), in-memory (ElastiCache), document (DocumentDB), graph (Neptune), wide-column (Keyspaces), time series (Timestream) and data warehouse (Redshift)](/diagrams/databases-types.dark.svg)
Each kind of data has a database built for it.
- **Relational** (SQL, [OLTP](/docs/glossary#term-oltp)): tables with a fixed schema, joined with SQL, with transactions. Good for orders, accounts and anything with relationships between records. **RDS** and **Aurora**. - **Key-value** ([NoSQL](/docs/glossary#term-nosql)): look up an item by its key, at any scale, with no joins. **DynamoDB**. - **In-memory**: data kept in RAM for sub-millisecond reads, mostly as a cache in front of another database. **ElastiCache**. - **Document**: JSON documents with flexible fields, queried by any field. **DocumentDB** (MongoDB-compatible). - **Graph**: things and the links between them, for questions like "friends of friends". **Neptune**. - **Wide-column**: Apache Cassandra tables, for huge write-heavy workloads. **Keyspaces**. - **Time series**: values measured over time, such as sensor readings. **Timestream**. - **Data warehouse** ([OLAP](/docs/glossary#term-olap)): SQL analytics over large amounts of history. **[Redshift](/docs/analytics/redshift)**, covered with Athena and EMR in the [Analytics](/docs/analytics) group. - **Object storage** ([S3](/docs/s3)) and **search** ([OpenSearch](/docs/analytics/opensearch)) also hold data, and are covered in their own groups. The slides list **Amazon Quantum Ledger Database (QLDB)** for ledger data. AWS has discontinued QLDB: its page now points to Aurora PostgreSQL instead. You won't need it for the exam. ## Choosing the right database [#choosing-the-right-database] Before picking a service, answer these questions about the workload: - **Reads and writes:** read-heavy, write-heavy or balanced? How much throughput, and does it change during the day? - **Size and growth:** how much data, for how long, and how big is each item? How is it accessed? - **Durability:** is this the source of truth, or a copy you can rebuild (a cache)? - **Latency and concurrency:** milliseconds or microseconds? How many users at once? - **Data model:** structured, semi-structured or connected? Do you need joins, or simple lookups by key? - **Schema:** fixed and strict, or changing often? Do you need reporting or search? - **Licences:** paying for Oracle or SQL Server licences? Moving to Aurora removes them. An online shop might use three databases. Orders and payments live in **Aurora**, because they need transactions and joins. The shopping cart and session data live in **DynamoDB**, because every request reads one cart by its key. Product pages are cached in **ElastiCache**, so the database isn't asked for the same page thousands of times a minute. ## In this group [#in-this-group] ### Relational: RDS [#relational-rds] ### Relational: Aurora [#relational-aurora] ### RDS and Aurora operations [#rds-and-aurora-operations] ### Caching [#caching] ### NoSQL [#nosql] ## Each service in one line [#each-service-in-one-line] - **RDS:** managed relational database for MySQL, PostgreSQL, MariaDB, Oracle, SQL Server or Db2. You choose the instance size and storage. For SQL, joins and transactions. - **Aurora:** AWS's own MySQL- and PostgreSQL-compatible engine. Storage is separate from compute and kept in six copies; more performance and less management than RDS. - **ElastiCache:** managed Valkey, Redis OSS or Memcached. In-memory key-value store, sub-millisecond. Needs application code changes. - **DynamoDB:** serverless NoSQL key-value tables, single-digit millisecond at any scale. Great for serverless apps and fast-changing schemas. - **DocumentDB:** MongoDB-compatible document database. **Neptune:** graph database. **Keyspaces:** Cassandra-compatible tables. **Timestream:** time series. - **S3:** objects of any size by key; great for big files, not for many tiny items. Covered in the [Amazon S3](/docs/s3) group. ## Exam tips [#exam-tips] - **"Relational", "SQL", "joins", "transactions", "OLTP"** → RDS or Aurora. - **"MySQL or PostgreSQL with the best performance and availability", "less management"** → Aurora. - **"Oracle or SQL Server with access to the operating system"** → RDS Custom. - **"Serverless NoSQL", "key-value", "millions of requests per second", "schema changes often"** → DynamoDB. - **"Cache", "sub-millisecond", "session store", "reduce database load"** → ElastiCache (or DAX for DynamoDB). - **"MongoDB"** → DocumentDB. **"Graph", "relationships", "social network", "fraud rings"** → Neptune. **"Cassandra", "CQL"** → Keyspaces. **"Time series", "IoT sensor data"** → Timestream. - **"Analytics", "data warehouse", "OLAP", "BI"** → Redshift. ## Common traps [#common-traps] - **"DynamoDB for complex joins and reporting."** DynamoDB has no joins; use a relational database or Redshift. - **"ElastiCache as the main database."** It's a cache: fast, but the source of truth should be a durable database. - **"RDS for a schema that changes every week with millions of writes a second."** That's a NoSQL workload; DynamoDB fits better. ## AWS documentation [#aws-documentation] - [Choosing an AWS database service](https://docs.aws.amazon.com/decision-guides/latest/databases-on-aws-how-to-choose/databases-on-aws-how-to-choose.html) - [What is Amazon RDS?](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html) - [What is Amazon Aurora?](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_AuroraOverview.html) - [What is Amazon DynamoDB?](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) - [What is Amazon ElastiCache?](https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/WhatIs.html) # Read replicas and Multi-AZ (/docs/databases/rds-read-replicas-multi-az) ## Two different problems [#two-different-problems] RDS offers two kinds of extra copy of your database, and they solve different problems: - **Read replicas** solve **too many reads**. They are extra, read-only databases your application can query. They are about **scaling**. - **Multi-AZ** solves **an AZ or instance failure**. A standby copy waits in another AZ and takes over automatically. It is about **availability**. ## Read replicas [#read-replicas]
![Read replicas: the application writes to and reads from the primary instance; RDS copies changes asynchronously to read replicas, which serve reads only; replication to a replica in the same Region has no data transfer charge, while a replica in another Region is charged for transfer](/diagrams/databases-read-replicas.light.svg) ![Read replicas: the application writes to and reads from the primary instance; RDS copies changes asynchronously to read replicas, which serve reads only; replication to a replica in the same Region has no data transfer charge, while a replica in another Region is charged for transfer](/diagrams/databases-read-replicas.dark.svg)
Write to the primary, read from the replicas.
A **[read replica](/docs/glossary#term-read-replica)** is a read-only copy of a DB instance. 1. The application sends **writes** (and any reads it wants) to the **primary** instance. 2. RDS uses the engine's own replication to copy each change to the replicas **asynchronously**: the primary doesn't wait for them. So reads from a replica are **eventually consistent**; they may be a little behind. 3. The application sends **read-only queries** (`SELECT`) to a replica's own endpoint. Replicas can't take `INSERT`, `UPDATE` or `DELETE`. Key facts: - **Up to 15 read replicas** per source instance (for Oracle, AWS recommends keeping to 5). - A replica can be in the **same AZ**, **another AZ** or **another Region**. - Each replica has its **own DNS endpoint**. Your application must be changed to send reads there; RDS doesn't split reads for you. - You can **promote** a replica to a standalone database. Replication stops and it accepts writes. Useful for disaster recovery, or for splitting a database. - A replica can itself be **Multi-AZ**, for a replica that survives an AZ failure. - Replicas are billed as normal DB instances. ### Use case: reporting without slowing production [#use-case-reporting-without-slowing-production] A production database is busy with the shop's normal traffic. The business wants a reporting app that runs heavy analytics queries. Running them on the primary would slow the shop down. Instead you create a read replica and point the reporting app at it. The production app is unaffected. ### Network cost [#network-cost] In AWS, data moving from one AZ to another usually costs money. **RDS read replicas are an exception:** replication to a replica **in the same Region** has **no data transfer charge**, even in another AZ. Replication to a replica **in another Region** is charged. ## Multi-AZ [#multi-az]
![Multi-AZ: applications connect to one DNS endpoint that points to the primary instance in Availability Zone a; RDS replicates synchronously to a standby in Availability Zone b, which takes no traffic; on failover the DNS endpoint points to the standby](/diagrams/databases-multi-az.light.svg) ![Multi-AZ: applications connect to one DNS endpoint that points to the primary instance in Availability Zone a; RDS replicates synchronously to a standby in Availability Zone b, which takes no traffic; on failover the DNS endpoint points to the standby](/diagrams/databases-multi-az.dark.svg)
A standby in another AZ, one name for both.
A **[Multi-AZ deployment](/docs/glossary#term-multi-az-deployment)** keeps a **standby** instance in a different AZ. 1. The application connects to **one DNS endpoint**. 2. Every write to the primary is copied **synchronously** to the standby: a write only succeeds once both have it. No data is lost on failover. 3. If the primary fails (loss of the AZ, the network, the instance or its storage), RDS **fails over automatically**: the DNS name now points to the standby, which becomes the new primary. It usually takes a minute or two. 4. The application needs **no change**; it just reconnects to the same name. The standby **serves no traffic**: you can't read from it. Multi-AZ is for **availability, not for scaling**. It also makes backups and patching smoother, because RDS can work on the standby first. Read replicas can also be set up as Multi-AZ. And in a disaster you can promote a read replica in another Region, which Multi-AZ (one Region only) can't give you. ### Multi-AZ DB clusters [#multi-az-db-clusters] There's a newer option for MySQL and PostgreSQL: a **Multi-AZ DB cluster**. It has a **writer** and **two readable standbys** in three AZs. Replication is semisynchronous, failover is faster than with one standby, and the two readers can serve read traffic. The classic Multi-AZ with one hidden standby is called a **Multi-AZ DB instance deployment**. The slides describe only the one-standby Multi-AZ, where the standby can't be read. AWS has since added **Multi-AZ DB clusters** (MySQL and PostgreSQL) with two **readable** standbys. On the exam, "Multi-AZ" with "the standby can't serve reads" means the classic deployment. ### Going from Single-AZ to Multi-AZ [#going-from-single-az-to-multi-az] Turning on Multi-AZ is a **zero-downtime** change: you click **Modify** and choose Multi-AZ. Behind the scenes: 1. RDS takes a **snapshot** of the primary. 2. It **restores** that snapshot as a new standby in another AZ. 3. It sets up **synchronous replication** between the two, and the standby catches up. ## Read replicas vs Multi-AZ [#read-replicas-vs-multi-az] | | Read replica | Multi-AZ | | --- | --- | --- | | For | Scaling reads | Failover | | Copying | Async | Sync | | Reads | Yes | No | ## RDS Custom [#rds-custom] Normal RDS gives you no access to the operating system. **RDS Custom** does, for **Oracle** and **Microsoft SQL Server** only. - AWS still automates setup, backups and scaling, but you also get **full admin access** to the database and its EC2 instance. - You can change settings, install patches, and turn on features that need the OS. You connect with **SSH** or **SSM Session Manager**. - Before you customise, **pause the automation** (the slides call it *de-activating automation mode*) so RDS doesn't undo or fight your changes, and take a **snapshot** first. So: **RDS** = AWS manages the database and the OS. **RDS Custom** = you get the OS and database too, with AWS still doing the routine work. ## Real-world examples [#real-world-examples] - **A news site** gets 50 times more reads than writes. Three read replicas take the read traffic, and the primary handles the writes. - **A bank's core database** runs Multi-AZ. When an AZ has a power problem, RDS fails over in about a minute and the app reconnects by itself. - **A company with a legacy SQL Server app** needs a third-party agent installed on the database server. RDS Custom for SQL Server allows it. ## Exam tips [#exam-tips] - **"Read-heavy", "reporting queries slow down production", "scale reads"** → read replicas. - **"High availability", "survive an AZ failure", "automatic failover", "no data loss"** → Multi-AZ. - **"Replica lag", "reads may be stale"** → asynchronous read replicas. - **"Disaster recovery to another Region"** → cross-Region read replica (promote it). - **"Reduce cross-AZ replication cost"** → RDS replicas in the same Region are free to replicate to. - **"Make an existing database Multi-AZ with no downtime"** → modify it. ## Common traps [#common-traps] - **"Multi-AZ standby to offload reads."** The classic standby takes no traffic; use read replicas. - **"Read replicas for automatic failover."** Promotion is manual; Multi-AZ fails over automatically. - **"Change the application's connection string after a Multi-AZ failover."** Not needed: the DNS name stays the same. - **"Read replicas need no application change."** The app must send reads to the replica endpoints. ## Hands-on lab: add a read replica [#hands-on-lab-add-a-read-replica] **Goal:** create a read replica of a small database and see that it refuses writes. Two `db.t4g.micro` instances (primary and replica) with 20 GiB each: about **$0.04 an hour**. Delete both the same day. Any Region works. **Before you start:** create `saa-db` as in the [RDS lab](/docs/databases/rds#hands-on-lab-create-a-small-rds-database), connected to `saa-web`. ### Create the replica [#create-the-replica] Select `saa-db` → **Actions → Create read replica**. Identifier `saa-db-replica`, instance class `db.t4g.micro`, a **different AZ** from the primary, Public access No. Create. It takes about 10 minutes. ### Allow your instance to reach it [#allow-your-instance-to-reach-it] The replica uses the primary's security groups, so `saa-web` can already reach it. Copy the replica's **endpoint**: it differs from the primary's. ### Write to the primary, read from the replica [#write-to-the-primary-read-from-the-replica] From `saa-web`: ```bash psql -h -U postgres -c "create table t(x int); insert into t values (42);" psql -h -U postgres -c "select * from t;" psql -h -U postgres -c "insert into t values (1);" ``` The `select` on the replica returns 42. The `insert` fails with *cannot execute INSERT in a read-only transaction*. **Expected result:** data written to the primary shows up on the replica within seconds, and the replica refuses writes. **Clean up:** delete `saa-db-replica`, then `saa-db` (no final snapshot, no retained backups), then the two `rds-ec2-*` / `ec2-rds-*` security groups. ## AWS documentation [#aws-documentation] - [Working with DB instance read replicas](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReadRepl.html) - [Multi-AZ DB instance deployments](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZSingleStandby.html) - [Multi-AZ DB cluster deployments](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/multi-az-db-clusters-concepts.html) - [Amazon RDS Custom](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-custom.html) # Security and RDS Proxy (/docs/databases/rds-security-proxy) ## Security for RDS and Aurora [#security-for-rds-and-aurora] ### Encryption at rest [#encryption-at-rest] - RDS and Aurora encrypt the storage with **AWS KMS** keys. Encryption covers the data, logs, **automated backups**, **snapshots** and **read replicas**. - You choose encryption **when you create** the database. You can't switch it on for a running instance. - If the primary is **not encrypted**, its read replicas **can't be encrypted** either. - To encrypt an existing unencrypted database: take a **snapshot**, **copy** it with encryption turned on, then **restore** the encrypted copy as a new database (the same method as for [EBS volumes](/docs/storage/ebs-encryption)). ### Encryption in transit [#encryption-in-transit] Every RDS and Aurora database accepts **TLS** connections. Clients use the **AWS TLS root certificates** to check they are talking to the real database. You can force TLS with a parameter (for example `rds.force_ssl` for PostgreSQL). ### Authentication [#authentication] - **Username and password**, the normal way for each engine. Store the password in **AWS Secrets Manager**, which can rotate it for you. - **[IAM database authentication](/docs/glossary#term-iam-database-authentication)** for **MySQL, MariaDB and PostgreSQL**: instead of a password, the app asks RDS for an **authentication token** signed with its IAM role. The token lasts **15 minutes**. No password is stored in the app, and access is controlled with IAM policies. ### Network and access [#network-and-access] - **Security groups** control which sources can reach the database port (3306 for MySQL, 5432 for PostgreSQL). Allow the application's security group, not the internet. - Put databases in **private subnets** with Public access off. - **No SSH** into the instance, except with **RDS Custom**. ### Audit logs [#audit-logs] Turn on the engine's **audit and error logs** and publish them to **CloudWatch Logs**, where you can keep them longer and search or alert on them. ## RDS Proxy [#rds-proxy]
![RDS Proxy: many Lambda functions in a VPC connect to RDS Proxy in a private subnet, which pools and reuses a few connections to the RDS database; clients authenticate with IAM and the proxy reads database credentials from Secrets Manager](/diagrams/databases-rds-proxy.light.svg) ![RDS Proxy: many Lambda functions in a VPC connect to RDS Proxy in a private subnet, which pools and reuses a few connections to the RDS database; clients authenticate with IAM and the proxy reads database credentials from Secrets Manager](/diagrams/databases-rds-proxy.dark.svg)
Many clients, a few shared connections.
Every database connection uses memory and CPU on the database. Some apps open **thousands** of short connections: a burst of Lambda functions, each opening its own connection, can exhaust the database's connection limit and slow it down. **[RDS Proxy](/docs/glossary#term-rds-proxy)** is a fully managed **database proxy** that sits between the app and the database. 1. Clients connect to the **proxy endpoint** instead of the database. 2. The proxy keeps a **pool** of database connections and **shares** them between clients. Thousands of client connections become a few dozen database connections. 3. When a client can't be served at once, the proxy **queues** it instead of letting the database fall over. What you get: - **Efficiency:** less stress on database CPU and RAM, fewer open connections and fewer timeouts. - **Faster failover:** the proxy keeps client connections open during a failover and sends them to the new primary, cutting failover time for RDS and Aurora by **up to 66%**. - **Security:** you can **enforce IAM authentication** for clients, and the proxy reads the database credentials from **Secrets Manager**, so they never sit in your code. - **Serverless:** it scales automatically and is highly available across AZs. - **No code change** for most apps: just point them at the proxy endpoint. - Supports **RDS for MySQL, PostgreSQL, MariaDB and SQL Server**, and **Aurora MySQL and PostgreSQL**. - **Never publicly accessible:** it can only be reached from inside the VPC. ## Real-world examples [#real-world-examples] - **A serverless API** on Lambda scales to 3,000 concurrent functions during a sale. Without a proxy, the database hits its connection limit; with RDS Proxy, the functions share 100 connections. - **A healthcare app** must encrypt all data. The team creates its RDS instance with KMS encryption, forces TLS, and uses IAM authentication so no database password is in the code. - **An old unencrypted database** must be encrypted for an audit. The team snapshots it, copies the snapshot with encryption, and restores. ## Exam tips [#exam-tips] - **"Encrypt an existing unencrypted RDS database"** → snapshot, copy with encryption, restore. - **"Connect to RDS without a password, using IAM roles"** → IAM database authentication (MySQL, MariaDB, PostgreSQL). - **"Rotate database credentials automatically"** → Secrets Manager. - **"Lambda functions exhaust database connections", "too many connections"** → RDS Proxy. - **"Reduce failover time for applications"** → RDS Proxy. - **"Enforce IAM authentication to the database"** → RDS Proxy (or IAM database authentication). ## Common traps [#common-traps] - **"Turn on encryption for a running RDS instance."** It must be chosen at creation; use the snapshot method. - **"An encrypted read replica of an unencrypted primary."** Not possible. - **"Make RDS Proxy public so on-premises clients can use it."** The proxy is only reachable from inside the VPC (or a connected network). - **"Use IAM policies to grant SQL permissions on tables."** IAM authenticates the connection; table permissions are still granted inside the database. ## Hands-on lab: put RDS Proxy in front of a database [#hands-on-lab-put-rds-proxy-in-front-of-a-database] **Goal:** create an RDS Proxy for a small database and connect through it. RDS Proxy is billed per vCPU of the database (for small instances, a minimum of 2 vCPUs): about **$0.03 an hour**, plus the `db.t4g.micro` (about $0.02) and a Secrets Manager secret ($0.40 a month, prorated). Delete everything within the hour. Any Region works. **Before you start:** create `saa-db` as in the [RDS lab](/docs/databases/rds#hands-on-lab-create-a-small-rds-database), but under **Credentials management** choose **Managed in AWS Secrets Manager**. ### Create the proxy [#create-the-proxy] **RDS → Proxies → Create proxy**. Engine family **PostgreSQL**, identifier `saa-proxy`, target `saa-db`. Under **Authentication**, choose the Secrets Manager secret RDS created for `saa-db`. Keep **IAM authentication: Not required** for this test. Use the same subnets and the `ec2-rds-*` security group that lets `saa-web` in. Create; it takes a few minutes. ### Connect through the proxy [#connect-through-the-proxy] Copy the proxy **endpoint** (`saa-proxy.proxy-…`). From `saa-web`: ```bash psql -h -U postgres -c "select inet_server_addr();" ``` Use the password from the secret (**Secrets Manager → the secret → Retrieve secret value**). The query works through the proxy. ### Watch the connections [#watch-the-connections] Open `saa-proxy` → **Monitoring**. `ClientConnections` and `DatabaseConnections` show how client connections map to pooled database connections. **Expected result:** the app reaches the database through the proxy without any change except the endpoint. **Clean up:** delete `saa-proxy`, then `saa-db` (no final snapshot, no retained backups). Deleting the instance schedules its managed secret for deletion. Delete the `rds-ec2-*` and `ec2-rds-*` security groups. ## AWS documentation [#aws-documentation] - [Encrypting Amazon RDS resources](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.Encryption.html) - [IAM database authentication](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html) - [Amazon RDS Proxy](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy.html) - [Amazon RDS Proxy features](https://aws.amazon.com/rds/proxy/) # Amazon RDS (/docs/databases/rds) ## What it is [#what-it-is] **[Amazon RDS](/docs/glossary#term-amazon-rds)** (Relational Database Service) runs relational databases for you. You pick an engine, an instance size and some storage; AWS sets up the database server and keeps it running. Your application connects to an endpoint with the normal driver for that engine and sends SQL. RDS supports six engines: - **MySQL**, **PostgreSQL** and **MariaDB** (open source); - **Oracle** and **Microsoft SQL Server** (commercial, licence included or bring your own); - **IBM Db2**. **Aurora**, AWS's own MySQL- and PostgreSQL-compatible engine, is part of the RDS family but works differently. It has its own page: [Amazon Aurora](/docs/databases/aurora). ## Why use RDS instead of a database on EC2 [#why-use-rds-instead-of-a-database-on-ec2] You could install MySQL on an EC2 instance yourself. Then every job that keeps a database healthy is yours. RDS takes most of them away:
![Who does what: with a database on EC2 you patch the operating system and database, take backups, run a standby and replicas; with Amazon RDS, AWS does all of that, and in both cases you design the schema, queries, indexes and users](/diagrams/databases-rds-managed.light.svg) ![Who does what: with a database on EC2 you patch the operating system and database, take backups, run a standby and replicas; with Amazon RDS, AWS does all of that, and in both cases you design the schema, queries, indexes and users](/diagrams/databases-rds-managed.dark.svg)
What you stop doing when you move a database to RDS.
With RDS, AWS: - provisions the server and installs the database; - patches the operating system and the database engine in a **maintenance window** you choose; - takes **continuous backups**, so you can restore to any second in the last 1 to 35 days ([point-in-time restore](/docs/databases/backups-restore-cloning)); - gives you **monitoring dashboards** (CloudWatch metrics, Performance Insights); - adds **[read replicas](/docs/databases/rds-read-replicas-multi-az)** for read performance and a **Multi-AZ** standby for disaster recovery; - lets you scale **vertically** (a bigger instance class) and **horizontally** (more read replicas); - stores your data on **EBS** volumes. The trade-off: **you can't SSH into an RDS instance.** You only get the database connection. If you need the operating system, use [RDS Custom](/docs/databases/rds-read-replicas-multi-az#rds-custom) (Oracle and SQL Server) or run the database on EC2. ## Instances and storage [#instances-and-storage] When you create an RDS database you choose: - **The engine and version**, for example PostgreSQL 17. - **The DB instance class**, which sets CPU and memory, such as `db.t4g.micro` (burstable, for tests), `db.m7g.large` (general purpose) or `db.r7g.xlarge` (memory optimised). - **The storage type and size**: General Purpose SSD (`gp3` or `gp2`) or Provisioned IOPS SSD (`io2`, `io1`) for heavy I/O. - **The network:** a VPC, a DB subnet group (subnets in at least two AZs) and security groups. Databases normally sit in **private subnets**, with **Public access** set to No. ## Storage auto scaling [#storage-auto-scaling] Running out of disk space stops a database. **Storage auto scaling** grows the storage for you when it's nearly full, with no downtime. - You turn it on and set a **maximum storage threshold**, the most it may grow to (at least 10% above the current size). - RDS grows the storage when **all** of these are true: - free space is **10% or less** of the allocated storage; - the low-storage condition has lasted **at least 5 minutes**; - the previous storage change has finished optimising, and there have been fewer than four changes in the last 24 hours. - Each step adds the largest of: 10 GiB, 10% of the current size, or the growth predicted for the next 7 hours. - It works with every RDS engine, and suits **unpredictable workloads** where you can't plan the size. The slides say a new change waits until **6 hours** after the last one. The AWS documentation now says RDS waits until the previous change has **finished optimising**, with at most **four changes in 24 hours**. ## Limits and pricing [#limits-and-pricing] - You pay per **instance hour** (by instance class, more for Multi-AZ), per **GB-month of storage** and provisioned IOPS, and for **backup storage** beyond the free amount (free up to 100% of your provisioned storage in each Region). - Commercial engines can include the licence in the hourly price. - A **stopped** instance still pays for storage and backups. RDS **starts it again automatically after 7 days**. To keep a database off for longer, take a snapshot and delete it, then restore when needed. - Reserved Instances lower the price for steady databases (see [purchasing options](/docs/compute/purchasing-options)). ## Real-world examples [#real-world-examples] - **A web shop** moves its MySQL server from one EC2 instance to RDS MySQL with Multi-AZ. Patching and backups stop being a weekend job. - **A company running Oracle** moves to RDS for Oracle, keeping its PL/SQL code and the licence it already owns. - **A start-up's app** grows faster than planned. Storage auto scaling adds space before the disk fills, instead of an outage at 3 am. ## Exam tips [#exam-tips] - **"Managed relational database", "MySQL / PostgreSQL / Oracle / SQL Server", "less operational overhead"** → RDS. - **"Database storage grows unpredictably", "avoid running out of space"** → turn on storage auto scaling with a maximum threshold. - **"Need OS access or custom patches on Oracle or SQL Server"** → RDS Custom. **"Full control of any engine"** → database on EC2. - **"Stop a database for months to save money"** → snapshot, delete, restore later (a stopped instance restarts after 7 days). ## Common traps [#common-traps] - **"SSH into the RDS instance to tune the OS."** Not possible on normal RDS. - **"A stopped RDS instance costs nothing."** You still pay for storage and backups. - **"Storage auto scaling also scales the instance class."** It only grows storage; changing the instance class is a separate change. ## Hands-on lab: create a small RDS database [#hands-on-lab-create-a-small-rds-database] **Goal:** create a PostgreSQL database with storage auto scaling, connect to it from an EC2 instance, and look at what RDS set up. A Single-AZ `db.t4g.micro` with 20 GiB of `gp3` storage costs about **$0.02 an hour** in us-east-1, plus the EC2 instance you connect from. Delete it the same day and the lab costs a few cents. Any Region works. **Before you start:** you need the `saa-web` instance (or any Amazon Linux 2023 instance) in the default VPC, from the [EC2 basics lab](/docs/compute/ec2-basics). ### Create the database [#create-the-database] **RDS → Create database → Standard create**. Engine **PostgreSQL**, template **Dev/Test**, availability **Single-AZ DB instance**. DB instance identifier `saa-db`, master username `postgres`, choose **Self managed** credentials and set a password. Instance class `db.t4g.micro`. Storage `gp3`, 20 GiB, tick **Enable storage autoscaling** with a maximum of 30 GiB. ### Connect it to your instance [#connect-it-to-your-instance] Under **Connectivity**, choose **Connect to an EC2 compute resource** and pick `saa-web`. RDS creates two security groups so only that instance can reach port 5432. Keep **Public access: No**. Add the tag `Project=saa-lab` and create. It takes about 5 to 10 minutes. ### Look around [#look-around] Open `saa-db`. Note the **endpoint** (a DNS name, not an IP), the port, the **Maintenance & backups** tab (backup retention, maintenance window) and **Monitoring**. Under **Configuration**, see the storage auto scaling limit. ### Connect and run SQL [#connect-and-run-sql] Connect to `saa-web` with EC2 Instance Connect and run: ```bash sudo dnf install -y postgresql17 psql -h -U postgres -d postgres -c "select version();" ``` Enter the password. You see the PostgreSQL version: you're talking to a managed database you never logged in to. **Expected result:** a working PostgreSQL database reachable only from your EC2 instance, with backups and storage auto scaling already on. **Clean up:** delete `saa-db` (untick **Create final snapshot**, tick the acknowledgement; untick **Retain automated backups**). Then delete the two security groups RDS created (`rds-ec2-*` and `ec2-rds-*`) and stop or terminate `saa-web` if you don't need it. Check **Billing → Bills** the next day. ## AWS documentation [#aws-documentation] - [What is Amazon RDS?](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html) - [Managing capacity automatically with storage autoscaling](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIOPS.Autoscaling.html) - [Stopping an Amazon RDS DB instance temporarily](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_StopInstance.html) - [Amazon RDS quotas and constraints](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Limits.html) # Amazon Timestream (/docs/databases/timestream) Timestream is in the course but not on the current SAA-C03 list of in-scope services. Read it for the idea of a time series database; it's unlikely to be asked about directly. ## What it is [#what-it-is] A **time series** is a list of values measured over time: a sensor's temperature every second, a server's CPU every minute, a share price every trade. Time series data arrives fast, is almost always appended (rarely changed), and is queried by time window: "the average over the last hour". **[Amazon Timestream](/docs/glossary#term-amazon-timestream)** is a fully managed, fast, scalable, **serverless time series database**. - **Scales up and down automatically** to adjust capacity. - Stores and analyses **trillions of events per day**. - AWS claims it's **1,000 times faster** than relational databases for time series, at **one tenth of the cost**. - **Scheduled queries**, **multi-measure records** (several values in one record) and **SQL** support. - **Storage tiering:** recent data is kept **in memory** for fast queries; historical data moves to **cheaper magnetic storage** by rules you set. - **Built-in time series functions** find trends and patterns in near real time. - **Encryption** in transit and at rest. **Use cases:** IoT applications, operational monitoring, real-time analytics. ## Architecture [#architecture] Timestream sits in the middle of a time series pipeline: - **Data in** from **AWS IoT Core**, **Kinesis Data Streams** (often through **Lambda**), **Amazon MSK** or Kinesis through **Managed Service for Apache Flink**, and open-source agents such as **Prometheus** and **Telegraf**. - **Data out** to dashboards in **Amazon QuickSight** and **Grafana**, to **SageMaker** for machine learning, or any app over a **JDBC** connection. ## Availability change [#availability-change] Since **20 June 2025**, the original engine, now called **Amazon Timestream for LiveAnalytics**, is **closed to new customers**. Existing customers can keep using it. For new projects AWS recommends **Amazon Timestream for InfluxDB**, a managed version of the open-source **InfluxDB** time series database, with single-digit millisecond queries for real-time analytics. ## Real-world examples [#real-world-examples] - **A wind farm** sends readings from 500 turbines every second. Timestream keeps the last day in memory for live dashboards in Grafana, and years of history on cheaper storage for trend analysis. - **A DevOps team** stores server metrics from Telegraf agents and alerts when CPU trends upwards for an hour. ## Exam tips [#exam-tips] - **"Time series data", "IoT sensor readings over time", "metrics with timestamps"** → Timestream (Timestream for InfluxDB for new designs). - **"Recent data fast, old data cheap, automatically"** → Timestream's storage tiering. ## Common traps [#common-traps] - **"Store high-rate sensor time series in RDS."** It works at small scale, but a time series database is far faster and cheaper for it. ## AWS documentation [#aws-documentation] - [What is Amazon Timestream for LiveAnalytics?](https://docs.aws.amazon.com/timestream/latest/developerguide/what-is-timestream.html) - [Timestream for LiveAnalytics availability change](https://docs.aws.amazon.com/timestream/latest/developerguide/AmazonTimestreamForLiveAnalytics-availability-change.html) - [What is Timestream for InfluxDB?](https://docs.aws.amazon.com/timestream/latest/developerguide/timestream-for-influxdb.html) # AWS Backup (/docs/dr/aws-backup) ## What it is [#what-it-is]
![AWS Backup: from one console you create a backup plan with frequency and retention, assign resources to it by tag, such as EC2, EBS, S3, RDS, Aurora, DynamoDB, EFS, FSx and Storage Gateway volumes, and the backups are stored in a backup vault and can be copied to other Regions and accounts](/diagrams/dr-aws-backup.light.svg) ![AWS Backup: from one console you create a backup plan with frequency and retention, assign resources to it by tag, such as EC2, EBS, S3, RDS, Aurora, DynamoDB, EFS, FSx and Storage Gateway volumes, and the backups are stored in a backup vault and can be copied to other Regions and accounts](/diagrams/dr-aws-backup.dark.svg)
One plan for backups across many services.
**[AWS Backup](/docs/glossary#term-aws-backup)** is a fully managed service to **centrally manage and automate backups** across AWS services. - No need to create custom scripts and manual processes. - **Supported services:** - Amazon EC2 / Amazon EBS; - Amazon S3; - Amazon RDS (all DB engines) / Amazon Aurora / Amazon DynamoDB; - Amazon DocumentDB / Amazon Neptune; - Amazon EFS / Amazon FSx (Lustre, Windows File Server, NetApp ONTAP, OpenZFS); - AWS Storage Gateway (Volume Gateway); - and more today: Redshift, Timestream, SAP HANA on EC2, VMware VMs, CloudFormation stacks… - Supports **cross-Region backups**. - Supports **cross-account backups** (within AWS Organizations, with backup policies applied to all accounts). ## Backup plans [#backup-plans] - Supports **PITR** (point-in-time recovery) for supported services. - **On-demand** and **scheduled** backups. - **Tag-based** backup policies (for example, every resource tagged `backup=daily`). - You create backup policies known as **backup plans**: - backup frequency (every 12 hours, daily, weekly, monthly, cron expression); - backup window; - transition to **cold storage** (never, days, weeks, months, years); - retention period (always, days, weeks, months, years). - Backups are stored in **backup vaults**. ## AWS Backup Vault Lock [#aws-backup-vault-lock]
![AWS Backup Vault Lock: backups are written once into a locked vault and become write once, read many; attempts to delete them or shorten their retention are denied, even for the root user; in governance mode, users with sufficient IAM permissions can remove the lock, and in compliance mode nobody can after the grace time](/diagrams/dr-vault-lock.light.svg) ![AWS Backup Vault Lock: backups are written once into a locked vault and become write once, read many; attempts to delete them or shorten their retention are denied, even for the root user; in governance mode, users with sufficient IAM permissions can remove the lock, and in compliance mode nobody can after the grace time](/diagrams/dr-vault-lock.dark.svg)
Backups nobody can delete.
**[Vault Lock](/docs/glossary#term-aws-backup-vault-lock)** enforces a **WORM** (Write Once Read Many) state for all the backups you store in an AWS Backup vault. - An additional layer of defense to protect your backups against: - inadvertent or malicious **delete** operations; - updates that **shorten or alter retention** periods. - **Even the root user cannot delete backups** when it's enabled. - Two modes (not in the slides): - **governance mode:** users with enough IAM permissions can remove the lock; - **compliance mode:** after a grace time (a cooling-off period you set), **nobody** can change or delete the lock, not even AWS. A **logically air-gapped vault** goes further: it's locked in compliance mode and can be **shared with other accounts** (through RAM) so you can restore even if the owning account is compromised. AWS Backup also offers **restore testing** and **Backup Audit Manager** for compliance reports. ## Real-world examples [#real-world-examples] - **A company** tags production resources `backup=gold`; one backup plan backs them up every 12 hours, keeps 35 days, copies to a second Region and a separate backup account, and a compliance-mode Vault Lock protects the copies from ransomware. ## Exam tips [#exam-tips] - **"Centralize and automate backups across services and accounts"** → AWS Backup (+ Organizations backup policies). - **"Copy backups to another Region or account automatically"** → AWS Backup copy rules. - **"Backups must be immutable, protected even from root / ransomware"** → Backup Vault Lock (compliance mode). - **"Back up resources by tag"** → tag-based backup plans. ## Common traps [#common-traps] - **"AWS Backup only does EBS snapshots."** It covers many services, including S3, DynamoDB, RDS, EFS and FSx. - **"Vault Lock is the same as S3 Object Lock."** Vault Lock protects AWS Backup vaults; [S3 Object Lock](/docs/s3/object-lock-vault-lock#s3-object-lock) protects S3 objects. ## Hands-on lab: an on-demand backup [#hands-on-lab-an-on-demand-backup] **Goal:** back up a DynamoDB table with AWS Backup and see the recovery point. Backups of a tiny DynamoDB table cost a fraction of a cent per month. Any Region works. ### Create a table [#create-a-table] **DynamoDB → Create table**: `saa-backup-demo`, partition key `id` (String). Add one item. ### Back it up [#back-it-up] **AWS Backup → Protected resources → Create on-demand backup**: resource type DynamoDB, table `saa-backup-demo`, the **Default** vault, retention 1 day. ### See the recovery point [#see-the-recovery-point] **Backup vaults → Default**: a recovery point appears when the job completes. **Expected result:** a completed backup job and a recovery point you could restore to a new table. **Clean up:** delete the recovery point from the vault, then delete the table. ## AWS documentation [#aws-documentation] - [What is AWS Backup?](https://docs.aws.amazon.com/aws-backup/latest/devguide/whatisbackup.html) - [Feature availability by resource](https://docs.aws.amazon.com/aws-backup/latest/devguide/backup-feature-availability.html) - [Backup plans](https://docs.aws.amazon.com/aws-backup/latest/devguide/about-backup-plans.html) - [AWS Backup Vault Lock](https://docs.aws.amazon.com/aws-backup/latest/devguide/vault-lock.html) - [Logically air-gapped vault](https://docs.aws.amazon.com/aws-backup/latest/devguide/logicallyairgappedvault.html) # Disaster recovery strategies (/docs/dr/dr-strategies) ## Four strategies [#four-strategies]
![The four disaster recovery strategies: backup and restore recovers in hours from backups; pilot light keeps core data live with servers off and recovers in tens of minutes; warm standby runs a full copy at minimum size and recovers in minutes; multi-site active/active runs full production in both sites with near real-time recovery; cost rises as recovery gets faster](/diagrams/dr-strategies.light.svg) ![The four disaster recovery strategies: backup and restore recovers in hours from backups; pilot light keeps core data live with servers off and recovers in tens of minutes; warm standby runs a full copy at minimum size and recovers in minutes; multi-site active/active runs full production in both sites with near real-time recovery; cost rises as recovery gets faster](/diagrams/dr-strategies.dark.svg)
Faster recovery costs more.
From cheapest and slowest to most expensive and fastest (faster RTO): 1. **Backup and restore** (RPO/RTO: hours). 2. **Pilot light** (tens of minutes). 3. **Warm standby** (minutes). 4. **Hot site / multi-site active/active** (near real time). The first three are **active/passive**: the DR site doesn't serve traffic until a failover. All four can be used across AWS Regions. ## Backup and restore (high RPO) [#backup-and-restore-high-rpo]
![Backup and restore: on-premises data goes to Amazon S3 through Storage Gateway or Snowball, with lifecycle rules to Glacier; resources already in AWS such as EBS, RDS and Redshift take scheduled snapshots; after a disaster you restore EC2 from AMIs and databases from snapshots](/diagrams/dr-backup-restore.light.svg) ![Backup and restore: on-premises data goes to Amazon S3 through Storage Gateway or Snowball, with lifecycle rules to Glacier; resources already in AWS such as EBS, RDS and Redshift take scheduled snapshots; after a disaster you restore EC2 from AMIs and databases from snapshots](/diagrams/dr-backup-restore.dark.svg)
Cheap to keep, slow to recover.
- Back up data to AWS: from on premises through **Storage Gateway** or **Snowball** to **S3**, with **lifecycle rules** to Glacier. - In AWS, take **scheduled snapshots** of EBS, Redshift and RDS (or use [AWS Backup](/docs/dr/aws-backup)). - After a disaster, **re-create everything**: EC2 from **AMIs**, databases from snapshots (ideally with CloudFormation). - Cheap (you only pay for storage), but RPO and RTO are high. ## Pilot light [#pilot-light]
![Pilot light: Route 53 sends traffic to the corporate data center; the database is continuously replicated to an RDS instance that is always running in AWS, while the EC2 application servers are prepared but not running; on failover they are started and Route 53 points to AWS](/diagrams/dr-pilot-light.light.svg) ![Pilot light: Route 53 sends traffic to the corporate data center; the database is continuously replicated to an RDS instance that is always running in AWS, while the EC2 application servers are prepared but not running; on failover they are started and Route 53 points to AWS](/diagrams/dr-pilot-light.dark.svg)
The core is lit; the rest is ready to switch on.
- A **small version** of the app is always running in the cloud: the **critical core** (the pilot light), usually the **database**, kept in sync. - Very similar to backup and restore, but **faster**, because critical systems are already up. - Application servers are prepared (AMIs, templates) but **not running**; on failover, start them and switch DNS. ## Warm standby [#warm-standby]
![Warm standby: the full system runs in AWS at minimum size, a load balancer, an Auto Scaling group at its minimum and a running RDS secondary kept in sync; on failover Route 53 sends traffic to AWS and the Auto Scaling group scales to production load](/diagrams/dr-warm-standby.light.svg) ![Warm standby: the full system runs in AWS at minimum size, a load balancer, an Auto Scaling group at its minimum and a running RDS secondary kept in sync; on failover Route 53 sends traffic to AWS and the Auto Scaling group scales to production load](/diagrams/dr-warm-standby.dark.svg)
Everything runs, just small.
- The **full system is up and running**, but at **minimum size**. - Upon disaster, we **scale to production load** (Auto Scaling) and switch traffic with [Route 53 failover](/docs/edge/route53-routing-policies#failover-active-passive). ## Multi-site / hot site [#multi-site--hot-site]
![Multi-site active/active: full production runs both in the corporate data center and in AWS, and Route 53 sends traffic to both; the database is replicated to a running RDS secondary, so recovery takes seconds to minutes, at the highest cost](/diagrams/dr-multi-site.light.svg) ![Multi-site active/active: full production runs both in the corporate data center and in AWS, and Route 53 sends traffic to both; the database is replicated to a running RDS secondary, so recovery takes seconds to minutes, at the highest cost](/diagrams/dr-multi-site.dark.svg)
Both sites serve production all the time.
- **Very low RTO** (minutes or seconds), **very expensive**. - **Full production scale** is running on AWS and on premises, both **active**. ## All-AWS multi-Region [#all-aws-multi-region]
![All-AWS multi-Region: two Regions both run production behind load balancers and Auto Scaling groups, Route 53 sends traffic to both, and an Aurora Global Database replicates from the primary in Region A to the secondary in Region B, which can be promoted on failover](/diagrams/dr-multi-region.light.svg) ![All-AWS multi-Region: two Regions both run production behind load balancers and Auto Scaling groups, Route 53 sends traffic to both, and an Aurora Global Database replicates from the primary in Region A to the secondary in Region B, which can be promoted on failover](/diagrams/dr-multi-region.dark.svg)
Two Regions, one global database.
The same multi-site idea with two AWS Regions: production in both, Route 53 active-active, and **[Aurora Global Database](/docs/databases/aurora-advanced#aurora-global-database)** replicating to the secondary Region (promote it on failover). ## Disaster recovery tips [#disaster-recovery-tips] - **Backup:** - EBS snapshots, RDS automated backups and snapshots, etc.; - regular pushes to S3 / S3 IA / Glacier, lifecycle rules, cross-Region replication; - from on premises: Snowball or Storage Gateway. - **High availability:** - use Route 53 to migrate DNS from Region to Region; - RDS Multi-AZ, ElastiCache Multi-AZ, EFS, S3; - Site-to-Site VPN as a recovery from Direct Connect. - **Replication:** - RDS replication (cross-Region), Aurora + Global Databases; - database replication from on premises to RDS; - Storage Gateway. - **Automation:** - CloudFormation / Elastic Beanstalk to re-create a whole new environment; - recover / reboot EC2 instances with CloudWatch if alarms fail; - AWS Lambda functions for customized automations. - **Chaos:** Netflix has a "simian army" randomly terminating EC2 instances, to prove the system survives failures. (On AWS, the **Fault Injection Service** does this in a controlled way.) AWS **Resilience Hub** can check whether a workload is likely to meet its RPO and RTO targets. Test your DR plan regularly: an untested plan is a guess. ## Exam tips [#exam-tips] - **"Lowest cost, RPO/RTO of hours is fine"** → backup and restore. - **"Database must stay in sync, servers can start on failover, tens of minutes"** → pilot light. - **"Scaled-down full copy always running, minutes"** → warm standby. - **"Near-zero downtime, cost no object"** → multi-site active/active. - **"Multi-Region DR for a relational database with RPO of about a second"** → Aurora Global Database. ## Common traps [#common-traps] - **"Pilot light runs a small copy of the whole app."** Only the core (data) runs; that's warm standby. - **"Warm standby serves production traffic normally."** It's passive until failover; active/active is multi-site. ## Check yourself [#check-yourself] Pilot light or warm standby: replicate the database continuously (RDS cross-Region replica or Aurora Global Database), keep AMIs and templates ready; for a reliable sub-15-minute RTO, warm standby with a minimum Auto Scaling group is safer, and Route 53 failover switches traffic. Backup and restore: the cheapest strategy. ## AWS documentation [#aws-documentation] - [Disaster recovery options in the cloud](https://docs.aws.amazon.com/whitepapers/latest/disaster-recovery-workloads-on-aws/disaster-recovery-options-in-the-cloud.html) - [Disaster Recovery of Workloads on AWS](https://docs.aws.amazon.com/whitepapers/latest/disaster-recovery-workloads-on-aws/disaster-recovery-workloads-on-aws.html) # AWS Elastic Disaster Recovery (/docs/dr/elastic-disaster-recovery) ## What it is [#what-it-is]
![AWS Elastic Disaster Recovery: a replication agent on each source server continuously replicates its disks at block level, within seconds, to a low-cost staging area of EC2 instances and EBS volumes; on a disaster, recovery instances launch in minutes from the latest or an earlier point in time, and you fail back to the source once it is repaired](/diagrams/dr-elastic-dr.light.svg) ![AWS Elastic Disaster Recovery: a replication agent on each source server continuously replicates its disks at block level, within seconds, to a low-cost staging area of EC2 instances and EBS volumes; on a disaster, recovery instances launch in minutes from the latest or an earlier point in time, and you fail back to the source once it is repaired](/diagrams/dr-elastic-dr.dark.svg)
Replicate in seconds, recover in minutes.
**[AWS Elastic Disaster Recovery](/docs/glossary#term-aws-elastic-disaster-recovery)** (DRS) used to be named **CloudEndure Disaster Recovery**. - Quickly and easily **recover** your **physical, virtual and cloud-based servers** into AWS. - **Example:** protect your most critical databases (including Oracle, MySQL and SQL Server), enterprise apps (SAP), protect your data from **ransomware** attacks… - **Continuous block-level replication** for your servers (within seconds), to a **staging area** of low-cost EC2 instances and EBS volumes. - **Failover** in **minutes**: launch recovery instances from the latest state or a **previous point in time** (useful against ransomware). - Run non-disruptive **recovery drills**, and **fail back** to the source when it's repaired. - Cheap while waiting: you pay for low-cost replication servers and storage, not a full standby environment. **DRS vs MGN:** both use the same replication technology. [Application Migration Service](/docs/migration/application-discovery-mgn#aws-application-migration-service-mgn) moves servers **once** (migration); Elastic Disaster Recovery keeps them **replicated** for recovery. ## Exam tips [#exam-tips] - **"Recover on-premises servers into AWS within minutes, low RPO (seconds)"** → Elastic Disaster Recovery. - **"CloudEndure Disaster Recovery"** → Elastic Disaster Recovery. - **"Recover to a point in time before a ransomware attack"** → DRS point-in-time recovery. ## Common traps [#common-traps] - **"Use DRS to migrate servers."** For a one-time move, use MGN. ## Check yourself [#check-yourself] DRS charges per replicated server hour, so instead: AWS Elastic Disaster Recovery: continuous block-level replication to a low-cost staging area, with recovery instances launched in minutes on failover. ## AWS documentation [#aws-documentation] - [What is Elastic Disaster Recovery?](https://docs.aws.amazon.com/drs/latest/userguide/what-is-drs.html) # Disaster Recovery & Backup (/docs/dr) ## Disaster recovery overview [#disaster-recovery-overview] - Any event that has a **negative impact** on a company's business continuity or finances is a **disaster**. - **Disaster recovery (DR)** is about **preparing for** and **recovering from** a disaster. - What kind of disaster recovery? - **On premises → on premises:** traditional DR, and very expensive (a second data center); - **On premises → AWS Cloud:** hybrid recovery; - **AWS Cloud Region A → AWS Cloud Region B.** - You need to define two terms: **RPO** and **RTO**. ## RPO and RTO [#rpo-and-rto]
![RPO and RTO on a timeline: the recovery point objective is the last backup before the disaster, so the time between them is the data you lose; the recovery time objective is when you are back online after the disaster, so the time between them is your downtime](/diagrams/dr-rpo-rto.light.svg) ![RPO and RTO on a timeline: the recovery point objective is the last backup before the disaster, so the time between them is the data you lose; the recovery time objective is when you are back online after the disaster, so the time between them is your downtime](/diagrams/dr-rpo-rto.dark.svg)
How much data you lose, and how long you're down.
- **[RPO](/docs/glossary#term-rpo)** (Recovery Point Objective): how **far back** your last good copy of the data is. If you back up every hour, you can lose up to an hour of data. **RPO = data loss.** - **[RTO](/docs/glossary#term-rto)** (Recovery Time Objective): how **long** it takes to get back online after the disaster. **RTO = downtime.** - Smaller RPO and RTO cost more: more frequent replication, more resources running all the time. For example, a bank's payments system might need an RPO of seconds and an RTO of minutes; an internal wiki might accept an RPO of 24 hours and an RTO of a day. ## In this group [#in-this-group] ## Exam tips [#exam-tips] - **"How much data can we afford to lose?"** → RPO. **"How long can we be down?"** → RTO. - Match the strategy to the RPO/RTO and the budget (see [DR strategies](/docs/dr/dr-strategies)). ## Common traps [#common-traps] - **"RTO is how much data we lose."** That's RPO; RTO is the downtime. ## AWS documentation [#aws-documentation] - [Disaster Recovery of Workloads on AWS](https://docs.aws.amazon.com/whitepapers/latest/disaster-recovery-workloads-on-aws/disaster-recovery-workloads-on-aws.html) - [Business continuity plan (BCP)](https://docs.aws.amazon.com/whitepapers/latest/disaster-recovery-workloads-on-aws/business-continuity-plan-bcp.html) # Amazon CloudFront (/docs/edge/cloudfront) ## What it is [#what-it-is] **[Amazon CloudFront](/docs/glossary#term-amazon-cloudfront)** is AWS's **content delivery network (CDN)**. It improves **read performance** by **caching** your content at the **edge**, close to your users, so they get a faster experience. - **Hundreds of points of presence** worldwide: edge locations plus larger regional edge caches. - **DDoS protection**, because it's spread worldwide, with **[AWS Shield](/docs/security/waf-shield-firewall-manager#aws-shield)** included and **[AWS WAF](/docs/security/waf-shield-firewall-manager#aws-waf)** integration. - Requests that do go back to your origin travel over the **AWS backbone**, not the public internet. ## How it works [#how-it-works]
![A CloudFront request: the viewer asks the nearest edge location for /beach.jpg; on a cache hit the edge answers from its cache; on a miss it fetches the file from the origin, an S3 bucket or HTTP server, over the AWS network and caches it for its TTL](/diagrams/edge-cloudfront-flow.light.svg) ![A CloudFront request: the viewer asks the nearest edge location for /beach.jpg; on a cache hit the edge answers from its cache; on a miss it fetches the file from the origin, an S3 bucket or HTTP server, over the AWS network and caches it for its TTL](/diagrams/edge-cloudfront-flow.dark.svg)
Hit: answer from the edge. Miss: fetch from the origin.
1. You create a **distribution** with one or more **origins** (where the real content lives). It gets a name like `d111111abcdef8.cloudfront.net`, and usually an alias record for your own domain. 2. A viewer's request (for example `GET /beach.jpg`) goes to the **edge location** with the lowest latency for them. 3. **Cache hit:** the edge has the file and answers at once. 4. **Cache miss:** the edge forwards the request to the origin, returns the response and **caches** it for the **TTL**, so the next viewers nearby get it from the edge. ## Origins [#origins] - **S3 bucket:** for distributing files and caching them at the edge, and even for **uploading** files to S3 through CloudFront. Secured with **origin access control (OAC)**. - **VPC origin:** for applications in **private subnets**: a private ALB, NLB or EC2 instance. - **Custom origin (HTTP):** any HTTP server, such as an **S3 static website** (the website feature must be turned on first), a **public ALB**, an EC2 instance, API Gateway or a Lambda function URL. - **Origin groups** pair a **primary** and a **secondary** origin: if the primary fails or returns certain error codes, CloudFront retries on the secondary (origin failover). ### S3 as an origin, with OAC [#s3-as-an-origin-with-oac]
![An S3 origin with origin access control: viewers reach the private bucket only through CloudFront, which signs its requests with OAC; the bucket policy allows only that distribution, so direct requests to S3 are denied](/diagrams/edge-cloudfront-oac.light.svg) ![An S3 origin with origin access control: viewers reach the private bucket only through CloudFront, which signs its requests with OAC; the bucket policy allows only that distribution, so direct requests to S3 are denied](/diagrams/edge-cloudfront-oac.dark.svg)
The bucket stays private; only CloudFront can read it.
- **[Origin access control (OAC)](/docs/glossary#term-origin-access-control)** makes CloudFront sign its requests to S3. - The **bucket policy** allows `s3:GetObject` only to the CloudFront service for **that distribution**. The bucket stays private, with Block Public Access on, and users can't bypass CloudFront. - OAC replaces the older **origin access identity (OAI)**: OAC also works with **SSE-KMS** encrypted objects, all Regions, and `PUT`/`DELETE` requests. ### ALB or EC2 as an origin [#alb-or-ec2-as-an-origin] **With VPC origins** (recommended): CloudFront reaches a **private** ALB, NLB or EC2 instance in a private subnet through a network interface it creates in your VPC. The application isn't exposed to the internet at all, and CloudFront is the **single way in**. (The VPC still needs an internet gateway, though CloudFront traffic doesn't use it.)
![CloudFront VPC origins: CloudFront delivers content from a private Application Load Balancer, Network Load Balancer or EC2 instance in a private subnet, so the origin needs no public IP address and CloudFront is the single way in](/diagrams/edge-vpc-origins.light.svg) ![CloudFront VPC origins: CloudFront delivers content from a private Application Load Balancer, Network Load Balancer or EC2 instance in a private subnet, so the origin needs no public IP address and CloudFront is the single way in](/diagrams/edge-vpc-origins.dark.svg)
Private origins with no public address.
**Over the public network** (the older way): - an **EC2 instance** origin must be **public**, and its security group must allow the **public IP ranges of CloudFront edge locations**; - an **ALB** origin must be **public** and allow the edge IP ranges; the **EC2 instances behind it can be private**, allowing only the ALB's security group. ## CloudFront vs S3 Cross-Region Replication [#cloudfront-vs-s3-cross-region-replication] - **CloudFront:** a global edge network; files are **cached for a TTL** (maybe a day). Great for **static content that must be available everywhere**. - **[S3 Cross-Region Replication](/docs/s3/versioning-replication#replication):** must be set up for **each Region** you want; files are updated in **near real time**; replicas are **read-only**. Great for **dynamic content that must be available at low latency in a few Regions**. ## Geo restriction [#geo-restriction] You can restrict **who can access** your distribution by country: - **Allowlist:** users can access your content **only** if they're in an approved country. - **Blocklist:** users in banned countries **can't** access it. The country comes from a **third-party GeoIP database** (about 99.8% accurate). **Use case:** copyright laws that limit where content can be shown. ## Cache invalidations [#cache-invalidations] If you update the origin, CloudFront doesn't know: edges keep serving the old copy until its **TTL** expires. A **[CloudFront invalidation](/docs/glossary#term-cloudfront-invalidation)** forces a refresh, bypassing the TTL: - invalidate **everything** (`/*`) or a **path** (`/images/*`, `/index.html`); - the first **1,000 invalidation paths each month are free**; a wildcard path counts as one; - paths are **case-sensitive**. The alternative is **versioned file names** (`style.v2.css`): new names are fetched fresh with no invalidation at all. ## Signed URLs and signed cookies [#signed-urls-and-signed-cookies] To serve **private content** only to some users (for example, paying customers), CloudFront can require **signed URLs** or **signed cookies**, created by your app with a key from a **trusted key group**: - **Signed URL:** access to **one file**, for clients that can't use cookies. - **Signed cookie:** access to **many files**, such as all the videos of a course, without changing URLs. These differ from [S3 presigned URLs](/docs/s3/presigned-urls), which grant access to one S3 object directly, using the signer's IAM permissions, with no CDN. ## Price classes [#price-classes] CloudFront charges different rates in different parts of the world. A **price class** lets you leave out the most expensive edge locations: - **Price Class All:** every location, best performance. - **Price Class 200:** most locations, excluding the most expensive ones. - **Price Class 100:** only the cheapest locations (North America and Europe). Origin groups, signed URLs and cookies, and price classes aren't in this edition of the course slides, but they're common CloudFront exam topics. These sections are written from the AWS documentation. AWS has also added **flat-rate pricing plans** that bundle CloudFront with WAF, Route 53 DNS and more for a fixed monthly price; that's newer than the exam material. ## Real-world examples [#real-world-examples] - **A news site** serves images and pages through CloudFront from a private S3 bucket with OAC. Traffic spikes hit the edge, not the bucket. - **A video streaming service** restricts some films to certain countries with geo restriction, and gives subscribers signed cookies. - **An internal-facing app** moves its ALB into private subnets and serves it through a CloudFront VPC origin, removing every public entry point except CloudFront. ## Exam tips [#exam-tips] - **"Cache static content globally", "reduce load on the origin", "low latency for users worldwide"** → CloudFront. - **"Only allow access to the S3 content through CloudFront"** → origin access control (OAC) and a bucket policy. - **"Origin in a private subnet without public exposure"** → CloudFront VPC origin. - **"Block users from certain countries"** → CloudFront geo restriction. - **"Users see old content after an update"** → invalidation (or versioned file names). - **"Paid content for many files per user"** → signed cookies. **"One file"** → signed URL. - **"Reduce CloudFront cost, users only in North America and Europe"** → Price Class 100. - **"High availability between two origins"** → origin group (origin failover). - **"Static content everywhere vs dynamic content in a few Regions"** → CloudFront vs S3 CRR. ## Common traps [#common-traps] - **"Make the bucket public so CloudFront can read it."** Use OAC and keep it private. - **"OAI is the recommended way."** OAI is legacy; OAC is recommended (and needed for SSE-KMS). - **"CloudFront updates its cache immediately when S3 changes."** Only after the TTL, or an invalidation. - **"S3 presigned URLs and CloudFront signed URLs are the same."** Different services, different keys. ## Hands-on lab: CloudFront in front of a private bucket [#hands-on-lab-cloudfront-in-front-of-a-private-bucket] **Goal:** serve a private S3 bucket through CloudFront with OAC, and see direct access denied. A distribution with a handful of requests costs **less than a cent** (or nothing on the CloudFront free plan). Deleting it takes a few minutes. Any Region works for the bucket. ### Prepare a private bucket [#prepare-a-private-bucket] Create a bucket `saa-cf-` (Block Public Access on) and upload `index.html` containing `

Hello from CloudFront

`.
### Create the distribution [#create-the-distribution] **CloudFront → Create distribution**. Origin: choose your bucket (the REST endpoint, not the website endpoint). **Origin access: Origin access control settings (recommended)** → create a new OAC. Default root object `index.html`. Skip WAF for this lab. Create. When it shows the bucket policy to copy, copy it. ### Allow CloudFront in the bucket policy [#allow-cloudfront-in-the-bucket-policy] In the bucket's **Permissions → Bucket policy**, paste the policy (it allows `cloudfront.amazonaws.com` with a condition on your distribution's ARN). Save. ### Test [#test] When the distribution is deployed, open `https://.cloudfront.net`: "Hello from CloudFront", over HTTPS. Open the S3 object URL directly: **AccessDenied**. Update `index.html`, reload: still the old page until you create an invalidation for `/index.html`.
**Expected result:** content served worldwide over HTTPS from a bucket nobody can reach directly. **Clean up:** **Disable** the distribution, wait until it's deployed, **Delete** it, delete the OAC, then empty and delete the bucket. ## AWS documentation [#aws-documentation] - [What is Amazon CloudFront?](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) - [Use various origins with CloudFront distributions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/DownloadDistS3AndCustomOrigins.html) - [Restrict access to an Amazon S3 origin](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html) - [Restrict access with VPC origins](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-vpc-origins.html) - [Restrict the geographic distribution of your content](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/georestrictions.html) - [Invalidate files to remove content](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html) - [Serve private content with signed URLs and signed cookies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html) - [Optimize high availability with origin failover](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/high_availability_origin_failover.html) # DNS basics (/docs/edge/dns-basics) ## What it is [#what-it-is] Computers find each other by **IP address**, such as `172.217.18.36`. People prefer names, such as `www.google.com`. The **[Domain Name System (DNS)](/docs/glossary#term-dns)** translates the human-friendly names into the machine addresses. DNS is the backbone of the internet: almost every connection starts with a DNS lookup. It uses a **hierarchy** of names, read from right to left: `.com`, then `example.com`, then `www.example.com` or `api.example.com`. ## The parts of a name [#the-parts-of-a-name]
![The parts of a domain name in http://api.www.example.com.: the protocol http://, the subdomain api.www., the second-level domain example, the top-level domain .com and the root, the final dot; everything after the protocol is the fully qualified domain name](/diagrams/edge-domain-name.light.svg) ![The parts of a domain name in http://api.www.example.com.: the protocol http://, the subdomain api.www., the second-level domain example, the top-level domain .com and the root, the final dot; everything after the protocol is the fully qualified domain name](/diagrams/edge-domain-name.dark.svg)
A domain name, read from right to left.
- **Root:** the final dot, usually hidden. Every name hangs from it. - **Top-level domain (TLD):** `.com`, `.org`, `.gov`, `.us`, `.in` and so on. - **Second-level domain (SLD):** the name you register, such as `example.com`, `amazon.com`. - **Subdomain:** anything to the left, such as `www.` or `api.www.`. - **Fully qualified domain name (FQDN):** the complete name down to the root, such as `api.www.example.com.`. - The **protocol** (`http://`) and path are part of the URL, not of the domain name. ## DNS terms [#dns-terms] - **Domain registrar:** the company you buy (register) a domain from, such as Amazon Route 53 or GoDaddy. - **DNS records:** entries that say what a name points to, such as A, AAAA, CNAME and NS records (see [records](/docs/edge/route53-records-zones)). - **Zone file:** the set of DNS records for a domain. - **Name server:** a server that answers DNS queries. An **authoritative** name server holds the real records for a domain; a **non-authoritative** one (a resolver) answers from what it learned and cached. ## How a name is resolved [#how-a-name-is-resolved]
![How a name is resolved: the browser asks its local DNS resolver for example.com; the resolver asks a root name server, which points to the .com servers; the .com top-level domain server points to the authoritative servers for example.com; the authoritative server answers with the IP address 9.10.11.12, which the resolver caches and returns](/diagrams/edge-dns-resolution.light.svg) ![How a name is resolved: the browser asks its local DNS resolver for example.com; the resolver asks a root name server, which points to the .com servers; the .com top-level domain server points to the authoritative servers for example.com; the authoritative server answers with the IP address 9.10.11.12, which the resolver caches and returns](/diagrams/edge-dns-resolution.dark.svg)
Three questions to find one address.
When your browser wants `example.com`: 1. It asks the **local DNS resolver**, run by your company or ISP (or a public one). 2. If the resolver doesn't have the answer cached, it asks a **root name server** (managed by ICANN): "Who knows about `.com`?" The root answers with the `.com` name servers (an **NS** record). 3. The resolver asks the **TLD name server** for `.com` (managed by IANA, part of ICANN): "Who knows about `example.com`?" It answers with the name servers for `example.com`. 4. The resolver asks the **authoritative name server** for `example.com` (run by the domain's DNS service, such as Route 53). It answers: `example.com` is `9.10.11.12`. 5. The resolver **caches** the answer for the record's **TTL** and returns it to the browser, which also caches it. The browser then connects to `9.10.11.12`. Because of caching, most lookups are answered in step 1 without asking anyone else. ## Amazon Route 53 [#amazon-route-53] **Route 53** is AWS's DNS service: - a highly available, scalable, fully managed **authoritative** DNS: *authoritative* means **you** control and can update the records; - also a **domain registrar**; - able to **check the health** of your resources; - the **only AWS service with a 100% availability SLA**. The name comes from **port 53**, the traditional DNS port. ## Exam tips [#exam-tips] - **"Authoritative DNS where you manage the records"** → Route 53 hosted zone. - **"Changes to DNS take time to reach users"** → resolvers cache answers for the TTL. - **"Which AWS service has a 100% availability SLA?"** → Route 53. ## Common traps [#common-traps] - **"Route 53 is only a registrar."** It's also the DNS service and does health checks. - **"A DNS change is seen by everyone instantly."** Clients keep cached answers until the TTL expires. ## Check yourself [#check-yourself] DNS concepts are easiest to see from a terminal. In CloudShell (no cost), run `dig example.com` and `dig +trace example.com`; the second shows the root, `.com` and authoritative steps. Then try these: TLD `.com`; second-level domain `example.com`; subdomain `api.www`. Their resolvers cached the old answer and will keep it until the record's TTL runs out. Lowering the TTL before a planned change makes it take effect faster. ## AWS documentation [#aws-documentation] - [How DNS routes traffic to your web application](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/welcome-dns-service.html) - [Amazon Route 53 concepts](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/route-53-concepts.html) - [Amazon Route 53 Service Level Agreement](https://aws.amazon.com/route53/sla/) # Edge functions (/docs/edge/edge-functions) ## What it is [#what-it-is] Many modern applications run some logic **at the edge**, close to users. An **edge function** is code you write and attach to a **CloudFront distribution**. It runs near your users to cut latency. CloudFront offers two kinds: **CloudFront Functions** and **Lambda@Edge**. - **No servers** to manage; deployed **globally** for you. - **Use case:** customize the CDN content. - **Pay only for what you use.** Fully serverless. Uses include website security and privacy, dynamic web applications at the edge, search engine optimization (SEO), routing across origins and data centres, bot mitigation, real-time image transformation, A/B testing, user authentication and authorization, user prioritization, and user tracking and analytics. ## Where they run [#where-they-run]
![Where edge functions run: viewer request and viewer response happen between the viewer and CloudFront, origin request and origin response between CloudFront and the origin; CloudFront Functions run only on the viewer events, Lambda@Edge on all four](/diagrams/edge-function-triggers.light.svg) ![Where edge functions run: viewer request and viewer response happen between the viewer and CloudFront, origin request and origin response between CloudFront and the origin; CloudFront Functions run only on the viewer events, Lambda@Edge on all four](/diagrams/edge-function-triggers.dark.svg)
Four points where code can change a request or response.
- **Viewer request:** after CloudFront receives a request from a viewer. - **Origin request:** before CloudFront forwards the request to the origin (on a cache miss). - **Origin response:** after CloudFront receives the response from the origin. - **Viewer response:** before CloudFront sends the response to the viewer. ## CloudFront Functions [#cloudfront-functions] **[CloudFront Functions](/docs/glossary#term-cloudfront-functions)** are lightweight functions written in **JavaScript**. - For **high-scale, latency-sensitive** CDN customizations. - **Sub-millisecond** start-up and run time; **millions of requests per second**. - Change **viewer requests and responses** only. - A **native feature of CloudFront**: you write, test and publish the code entirely in CloudFront. - Can read data from **CloudFront KeyValueStore**, a small global key-value store (for example a list of redirects), updated separately from the code. Use them for: - **Cache key normalization:** transform request attributes (headers, cookies, query strings, URL) to make a better cache key; - **Header manipulation:** insert, modify or delete HTTP headers in the request or response; - **URL rewrites or redirects**; - **Request authentication and authorization:** create and check user-generated tokens (such as JWTs) to allow or deny requests. ## Lambda@Edge [#lambdaedge] **[Lambda@Edge](/docs/glossary#term-lambda-edge)** runs **Lambda functions** written in **Node.js or Python**. - Scales to **thousands of requests per second** (up to 10,000 per Region by default). - Can change all four events: **viewer request, origin request, origin response, viewer response**. - You write the function in **one Region, us-east-1 (N. Virginia)**, publish a numbered version, and CloudFront **replicates** it to its locations. Use it when you need: - **longer run times** (several milliseconds or more); - **adjustable CPU or memory**; - **third-party libraries**, such as the AWS SDK to call other AWS services; - **network access** to external services; - **file system access** or access to the **body** of HTTP requests. ## CloudFront Functions vs Lambda@Edge [#cloudfront-functions-vs-lambdaedge] - **Runtime:** JavaScript vs Node.js and Python. - **Scale:** millions vs thousands of requests per second. - **Triggers:** viewer request and response only vs all four. - **Run time:** under a millisecond vs up to 30 seconds. - **Memory:** 2 MB vs 128 MB (viewer events) up to 10 GB (origin events). - **Code size:** 10 KB vs 50 MB. - **Network and file system:** very limited (one call to an origin of the same distribution) vs full access. - **Request body:** no vs yes. - **Price:** about one sixth of Lambda@Edge, with a free allowance vs charged per request and duration. The slides give Lambda@Edge a maximum run time of **5 to 10 seconds** and code size of **1 to 50 MB**, and say CloudFront Functions have **no network access**. The AWS documentation now lists **30 seconds** and **50 MB** for all Lambda@Edge events, and allows CloudFront Functions **one network call to an origin** on the same distribution. The exam's rule of thumb is unchanged: quick header and URL changes → CloudFront Functions; heavy logic, network calls, request bodies → Lambda@Edge. ## Real-world examples [#real-world-examples] - **A news site** uses a CloudFront Function to redirect old URLs to new ones and to normalize query strings so more requests hit the cache. - **A photo service** uses Lambda@Edge on origin responses to resize images for each device, calling S3 with the AWS SDK. - **A media company** checks a signed JWT in a CloudFront Function on every viewer request, rejecting unauthorized users before they reach the origin. ## Exam tips [#exam-tips] - **"Lightweight, millions of requests per second, change headers, redirect URLs, normalize cache keys"** → CloudFront Functions. - **"Needs the AWS SDK", "network calls", "request body", "longer processing", "origin request or response"** → Lambda@Edge. - **"Authenticate users at the edge with a JWT"** → CloudFront Functions (simple check) or Lambda@Edge (complex). - **"Where do you create Lambda@Edge functions?"** → us-east-1. ## Common traps [#common-traps] - **"CloudFront Functions can run on origin requests."** Viewer events only. - **"Lambda@Edge functions can be written in any Region."** They're created in us-east-1 and replicated. - **"Use Lambda@Edge for simple header changes."** CloudFront Functions are faster and much cheaper. ## Check yourself [#check-yourself] An edge function lab needs a CloudFront distribution and takes a while to deploy and delete; try these instead: A CloudFront Function on the viewer response event: a simple header change at very high scale. Lambda@Edge on the origin request event: it needs the AWS SDK and network access, and runs only on cache misses. ## AWS documentation [#aws-documentation] - [Customize at the edge with functions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-functions.html) - [Differences between CloudFront Functions and Lambda@Edge](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-functions-choosing.html) - [Amazon CloudFront KeyValueStore](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/kvs-with-functions.html) - [Lambda@Edge function restrictions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-edge-function-restrictions.html) - [CloudFront quotas](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) # AWS Global Accelerator (/docs/edge/global-accelerator) ## The problem [#the-problem] You've deployed an application in one Region (say, behind a public ALB in India) and have **users all over the world**. They reach it over the **public internet**, through many hops between networks, which adds latency and makes it unpredictable. You'd like their traffic to get onto the fast AWS network as soon as possible. ## Unicast vs anycast [#unicast-vs-anycast]
![Unicast versus anycast: with unicast each server holds its own IP address and the client picks one; with anycast all servers share the same IP address and the client is routed to the nearest one](/diagrams/edge-anycast.light.svg) ![Unicast versus anycast: with unicast each server holds its own IP address and the client picks one; with anycast all servers share the same IP address and the client is routed to the nearest one](/diagrams/edge-anycast.dark.svg)
One address in many places.
- **Unicast IP:** one server holds one IP address. This is how most of the internet works. - **Anycast IP:** **all servers hold the same IP address**, and the network routes each client to the **nearest** one. ## How Global Accelerator works [#how-global-accelerator-works]
![Global Accelerator: without it, a user in Australia reaches a public load balancer in India over many public internet hops; with it, the user connects to one of two anycast IP addresses at the nearest edge location, and traffic crosses the AWS network to the load balancer](/diagrams/edge-global-accelerator.light.svg) ![Global Accelerator: without it, a user in Australia reaches a public load balancer in India over many public internet hops; with it, the user connects to one of two anycast IP addresses at the nearest edge location, and traffic crosses the AWS network to the load balancer](/diagrams/edge-global-accelerator.dark.svg)
Enter the AWS network at the nearest edge.
**[AWS Global Accelerator](/docs/glossary#term-aws-global-accelerator)** uses the AWS internal network to route users to your application: 1. It gives your application **two static anycast IP addresses** (four with IPv6 dual-stack). You can also bring your own IP addresses. 2. Those addresses are announced from every **edge location**, so each user's traffic enters AWS at the **nearest edge**. 3. From the edge, traffic crosses the **AWS global network** to your application's endpoints. Endpoints are **Elastic IP addresses, EC2 instances, ALBs and NLBs**, **public or private**, in **one or more Regions**. ### Why use it [#why-use-it] - **Consistent performance:** - intelligent routing to the **lowest-latency** healthy endpoint, and fast **regional failover**; - **no problems with client DNS caching**, because the IP addresses never change; - traffic stays on the AWS network. - **Health checks:** - Global Accelerator **health-checks** your endpoints and moves traffic away from unhealthy ones, typically in **under a minute** (AWS says it reacts instantly); - great for **disaster recovery** and for making an application global. - **Security:** - only **two external IP addresses** to put on allow lists; - **DDoS protection** with AWS Shield. - **Control:** **traffic dials** set the share of traffic per Region (endpoint group), and **endpoint weights** within a Region. Useful for blue/green deployments without changing IP addresses. A second type, the **custom routing accelerator**, maps each user to a specific EC2 instance and port; it's used for things like multiplayer game sessions. ## Global Accelerator vs CloudFront [#global-accelerator-vs-cloudfront] Both use the AWS global network and its edge locations around the world, and both integrate with **AWS Shield** for DDoS protection. - **CloudFront:** - improves performance for **cacheable content** (images, videos) and **dynamic content** (API acceleration, dynamic site delivery); - **content is served at the edge**, from cache. - **Global Accelerator:** - improves performance for a wide range of applications over **TCP or UDP**; - **proxies packets** at the edge to applications in one or more AWS Regions; **nothing is cached**; - good for **non-HTTP** uses: **gaming (UDP)**, **IoT (MQTT)**, **Voice over IP**; - good for HTTP uses that need **static IP addresses**; - good for HTTP uses that need **deterministic, fast regional failover**. ## Real-world examples [#real-world-examples] - **A multiplayer game** runs servers in three Regions. Players connect over UDP to two fixed IP addresses; Global Accelerator sends each to the nearest healthy Region. - **A payment API** must give banks two IP addresses to allow through their firewalls. Global Accelerator provides them, while the API runs behind ALBs in two Regions. - **An IoT fleet** has the endpoint IPs hard-coded in devices. Global Accelerator lets the company move the backend between Regions without updating a single device. ## Exam tips [#exam-tips] - **"Static IP addresses", "two IPs to allow-list", "IP addresses can't change"** → Global Accelerator. - **"UDP", "gaming", "VoIP", "IoT MQTT"** → Global Accelerator (CloudFront is for HTTP). - **"Fast regional failover, not affected by DNS caching"** → Global Accelerator. - **"Cache content at the edge"** → CloudFront, not Global Accelerator. - **"Shift a percentage of traffic between Regions without DNS changes"** → traffic dials. ## Common traps [#common-traps] - **"Global Accelerator caches content."** It doesn't; it only carries traffic. - **"Route 53 latency routing gives the same failover."** DNS answers are cached by clients; Global Accelerator's IPs stay the same, so failover doesn't wait for caches. - **"Global Accelerator only works with public endpoints."** Its endpoints can be private, such as internal ALBs. ## Check yourself [#check-yourself] An accelerator costs $0.025 an hour plus data transfer fees, and the benefit only shows with users far away, so instead of a lab: AWS Global Accelerator with two endpoint groups (one per Region) and health checks: clients use the two static anycast IPs, and failover doesn't depend on DNS caching. Amazon CloudFront: the content is cacheable, so serving it from edge caches beats proxying every request to the origin. ## AWS documentation [#aws-documentation] - [What is AWS Global Accelerator?](https://docs.aws.amazon.com/global-accelerator/latest/dg/what-is-global-accelerator.html) - [How AWS Global Accelerator works](https://docs.aws.amazon.com/global-accelerator/latest/dg/introduction-how-it-works.html) - [Benefits of Global Accelerator](https://docs.aws.amazon.com/global-accelerator/latest/dg/introduction-benefits-of-migrating.html) # DNS & Content Delivery (/docs/edge) ## What it is [#what-it-is] Most AWS services live in one Region. Users, though, are everywhere. The services in this group sit **in front of** your application, at AWS's **edge**, and help users reach it quickly and reliably from anywhere in the world.
![The three global edge services: Amazon Route 53 is DNS and turns names into addresses; Amazon CloudFront is a CDN that caches content near users; AWS Global Accelerator gives static IP addresses and carries traffic over the AWS backbone](/diagrams/edge-overview.light.svg) ![The three global edge services: Amazon Route 53 is DNS and turns names into addresses; Amazon CloudFront is a CDN that caches content near users; AWS Global Accelerator gives static IP addresses and carries traffic over the AWS backbone](/diagrams/edge-overview.dark.svg)
Three services between your users and your application.
- **[Amazon Route 53](/docs/glossary#term-amazon-route-53)** is AWS's **DNS** service. It turns names like `www.example.com` into IP addresses, and can choose *which* address to give each user: the nearest Region, a healthy server, a percentage split. - **[Amazon CloudFront](/docs/glossary#term-amazon-cloudfront)** is a **content delivery network (CDN)**. It keeps copies of your content in hundreds of **edge locations**, so users download it from nearby instead of from your Region. - **[AWS Global Accelerator](/docs/glossary#term-aws-global-accelerator)** gives your application **two static IP addresses** at the edge, then carries traffic over the AWS private network to your Region. It speeds up any TCP or UDP application, not only websites. The edge locations themselves are described in [global infrastructure](/docs/foundations/global-infrastructure#edge-locations-points-of-presence). A global online shop uses all three. **Route 53** answers `shop.example.com` with the address of a **CloudFront** distribution. CloudFront serves product images and pages from the edge, and sends checkout requests to load balancers in two Regions. A multiplayer game run by the same company uses **Global Accelerator**, because its players connect over UDP and need fixed IP addresses. ## In this group [#in-this-group] ### DNS: Route 53 [#dns-route-53] ### Content delivery [#content-delivery] ## Exam tips [#exam-tips] - **"Domain name", "DNS", "route users to the nearest Region", "DNS failover"** → Route 53. - **"Cache static content globally", "reduce latency for images and video", "offload the origin"** → CloudFront. - **"Static IP addresses for a global application", "TCP or UDP", "gaming", "fast regional failover without DNS caching"** → Global Accelerator. - **"Run code at the edge to change requests or responses"** → CloudFront Functions or Lambda@Edge. ## Common traps [#common-traps] - **"CloudFront for a UDP game."** CloudFront handles HTTP and HTTPS (and WebSocket); use Global Accelerator for UDP. - **"Route 53 routes the traffic."** It only answers DNS queries; the traffic itself never passes through Route 53. ## AWS documentation [#aws-documentation] - [What is Amazon Route 53?](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) - [What is Amazon CloudFront?](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) - [What is AWS Global Accelerator?](https://docs.aws.amazon.com/global-accelerator/latest/dg/what-is-global-accelerator.html) # CNAME vs alias (/docs/edge/route53-alias) ## The problem [#the-problem] AWS resources such as load balancers and CloudFront distributions give you an **AWS hostname**, like `lb1-1234.us-east-2.elb.amazonaws.com`. You want users to use your own name, like `myapp.mydomain.com`, or just `mydomain.com`. There are two ways to point your name at theirs.
![CNAME versus alias: a CNAME points a name such as app.mydomain.com to any other hostname, but not at the zone apex, its queries are charged and you set its TTL; an alias points a name, even the apex mydomain.com, to an AWS resource, with free queries to AWS targets and automatic tracking of IP address changes](/diagrams/edge-cname-alias.light.svg) ![CNAME versus alias: a CNAME points a name such as app.mydomain.com to any other hostname, but not at the zone apex, its queries are charged and you set its TTL; an alias points a name, even the apex mydomain.com, to an AWS resource, with free queries to AWS targets and automatic tracking of IP address changes](/diagrams/edge-cname-alias.dark.svg)
Two ways to point your name at an AWS name.
## CNAME [#cname] - Points a name to **any other name**: `app.mydomain.com` → `blabla.anything.com`. - **Only for names below the apex**, such as `something.mydomain.com`. Standard DNS doesn't allow a CNAME at the zone apex. - You set the TTL, and Route 53 charges for the queries. ## Alias records [#alias-records] An **[alias record](/docs/glossary#term-alias-record)** is a Route 53 extension to DNS that points a name to an **AWS resource**: `app.mydomain.com` → `blabla.amazonaws.com`. - Works for the **zone apex and below**: `mydomain.com` as well as `app.mydomain.com`. - Always of type **A** (IPv4) or **AAAA** (IPv6). Route 53 answers with the resource's current IP addresses. - **Automatically follows changes** in the resource's IP addresses: load balancer IPs change all the time, and the alias keeps up. - **Free:** queries for alias records pointing to AWS resources aren't charged. - **Native health check:** with *Evaluate target health* on, Route 53 stops answering with an unhealthy target. - **You can't set the TTL:** Route 53 uses the resource's own TTL. ### Alias targets [#alias-targets] An alias can point to: - **Elastic Load Balancing** load balancers; - **CloudFront** distributions; - **API Gateway** APIs; - **Elastic Beanstalk** environments; - **S3 buckets configured as websites**; - **VPC interface endpoints**; - **Global Accelerator** accelerators; - **App Runner** services; - **another Route 53 record in the same hosted zone**. **You can't create an alias for an EC2 instance's DNS name.** Point an A record at its (Elastic) IP address instead. ## Real-world examples [#real-world-examples] - **A company** wants `example.com` (no `www`) to reach its ALB. A CNAME isn't allowed at the apex, so it creates an **alias A record** to the ALB. - **A blog** points `www.example.com` with a **CNAME** to `example.github.io`, a non-AWS host, where an alias isn't possible. ## Exam tips [#exam-tips] - **"Point the root domain (zone apex) to a load balancer or CloudFront"** → alias record. - **"Point a name to a non-AWS hostname"** → CNAME (not at the apex). - **"Avoid DNS query charges for AWS resources"**, **"follow the load balancer's changing IPs"** → alias. - **"Alias to an EC2 instance"** → not possible; use an A record with an Elastic IP. ## Common traps [#common-traps] - **"Set a TTL of 60 seconds on an alias record."** You can't set the TTL on an alias to an AWS resource. - **"Create an A record with the load balancer's current IP."** Its IPs change; use an alias. - **"CNAME at the apex is fine in Route 53."** It isn't; that's what alias records are for. ## Check yourself [#check-yourself] An alias lab needs a public domain you own, so instead: An alias A (and AAAA) record for `example.com` with the CloudFront distribution as the target. A CNAME isn't allowed at the zone apex. A CNAME from `api.example.com` to `api.vendor.com`. It isn't an AWS resource, so an alias can't point to it, and it isn't the apex, so a CNAME is allowed. ## AWS documentation [#aws-documentation] - [Choosing between alias and non-alias records](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-choosing-alias-non-alias.html) - [Amazon Route 53 pricing (alias queries)](https://aws.amazon.com/route53/pricing/) # Health checks (/docs/edge/route53-health-checks) ## What it is [#what-it-is] A **[Route 53 health check](/docs/glossary#term-route-53-health-check)** regularly tests whether a resource is working. Linked to a record, it gives **automated DNS failover**: Route 53 stops answering with a resource that fails its check. For example, an app runs behind ALBs in us-east-1 and eu-west-1, with latency records for both. Each record has a health check. If eu-west-1 fails, Route 53 sends European users to us-east-1 until it recovers. Health checks are also published as **CloudWatch metrics**, so you can alarm on them. ## Three kinds of health check [#three-kinds-of-health-check]
![Three kinds of Route 53 health check: one that monitors an endpoint, from checkers around the world or from a source in your VPC; a calculated check that combines up to 255 child checks with AND, OR or NOT; and one that monitors a CloudWatch alarm on any metric](/diagrams/edge-health-check-types.light.svg) ![Three kinds of Route 53 health check: one that monitors an endpoint, from checkers around the world or from a source in your VPC; a calculated check that combines up to 255 child checks with AND, OR or NOT; and one that monitors a CloudWatch alarm on any metric](/diagrams/edge-health-check-types.dark.svg)
What a health check can watch.
1. **Health checks that monitor an endpoint:** an application, server or other resource. 2. **Calculated health checks:** monitor **other** health checks. 3. **Health checks that monitor a CloudWatch alarm:** full control, for example DynamoDB throttling, an RDS alarm or a custom metric. Useful for **private** resources. ## Monitoring an endpoint [#monitoring-an-endpoint] - **Health checkers** in locations around the world (about 15 in the slides) send requests to your endpoint. You can choose which locations to use. - **Interval:** every **30 seconds** (standard) or **10 seconds** (fast, costs more). - **Failure threshold:** how many checks in a row must fail (or pass) to change the status; **3** by default. - **Protocols:** HTTP, HTTPS and TCP. - The endpoint is **healthy** if **more than 18%** of the health checkers report it healthy; otherwise it's unhealthy. - An HTTP or HTTPS check passes only when the endpoint answers with a **2xx or 3xx** status code (within 2 seconds of connecting). - **String matching:** the check can also look for text in the **first 5,120 bytes** of the response. - Your firewall or security group must **allow requests from the Route 53 health checkers' IP ranges** (published in AWS's `ip-ranges.json`). ## Calculated health checks [#calculated-health-checks]
![A calculated health check: the parent is healthy when at least two of its three child health checks pass, and each child monitors one web server](/diagrams/edge-calculated-health.light.svg) ![A calculated health check: the parent is healthy when at least two of its three child health checks pass, and each child monitors one web server](/diagrams/edge-calculated-health.dark.svg)
One parent check combining several children.
- Combine the results of several health checks into **one**. - Use **OR**, **AND** or **NOT**, or say how many children must pass. - Up to **255 child** health checks. - **Use case:** take one web server down for maintenance without the parent check, and so the whole site, failing. ## Private resources [#private-resources] Route 53's public health checkers are **outside your VPC**, so they **can't reach private endpoints** (a private subnet, or an on-premises server over VPN or Direct Connect). Two options: - **CloudWatch alarm:** create a CloudWatch metric and alarm for the private resource (for example the EC2 `StatusCheckFailed` metric), then a health check that monitors the **alarm**. This is the method in the slides. - **Private endpoint health checks:** create a **health check source** in your VPC (it gets an IP address in each of three AZs), and Route 53 checks private endpoints from inside the VPC. One source can serve up to 200 checks. The slides say Route 53 health checks can't reach private resources, so you must use a CloudWatch alarm. AWS has since added **private endpoint health checks**, run from a source inside your VPC. Both answers now work; on the exam, the CloudWatch alarm method is still a correct choice. ## Pricing [#pricing] Up to 50 health checks of AWS endpoints in your account are free. After that, a basic check costs $0.50 a month for an AWS endpoint and $0.75 for a non-AWS endpoint. Optional features (HTTPS, string matching, fast interval, latency measurement) cost extra each. ## Exam tips [#exam-tips] - **"Automatic DNS failover to a healthy Region"** → health checks linked to records (failover, latency, weighted…). - **"Health check for a resource in a private subnet"** → health check on a CloudWatch alarm (or a private endpoint health check). - **"Keep the site healthy while one server is in maintenance"** → calculated health check. - **"Health checks keep failing although the app works"** → allow the Route 53 health checker IP ranges through the firewall. - **"Check that the page contains specific text"** → string matching (first 5,120 bytes). ## Common traps [#common-traps] - **"Route 53 public health checkers can reach private IPs."** They can't; use a CloudWatch alarm or a private endpoint health check. - **"A 404 means healthy because the server answered."** Only 2xx and 3xx pass. - **"Simple routing records can use health checks."** They can't. ## Hands-on lab: a health check on a website [#hands-on-lab-a-health-check-on-a-website] **Goal:** create a health check for a public web server and watch it turn unhealthy. A health check on an AWS endpoint is free (up to 50); the `saa-web` instance and its public IPv4 address cost about $0.02 an hour. Any Region works. **Before you start:** run `saa-web` with its web server from the [EC2 basics lab](/docs/compute/ec2-basics), with port 80 open. ### Create the health check [#create-the-health-check] **Route 53 → Health checks → Create health check**. Name `saa-web-hc`, monitor **Endpoint**, specify by **IP address**: the public IP of `saa-web`, protocol HTTP, port 80, path `/`. Keep the 30-second interval. Create. ### Watch it pass [#watch-it-pass] After a minute or two the status is **Healthy**. Open the **Health checkers** tab: each location reports its own result. ### Break it [#break-it] On `saa-web`, run `sudo systemctl stop httpd`. Within about two minutes the health check turns **Unhealthy**. Start the web server again and it recovers. **Expected result:** a health check that follows the state of your web server, ready to drive DNS failover. **Clean up:** delete `saa-web-hc`. Stop or terminate `saa-web` if you don't need it. ## AWS documentation [#aws-documentation] - [Types of Amazon Route 53 health checks](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-types.html) - [How Route 53 determines whether a health check is healthy](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html) - [Configuring failover in a private hosted zone](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html) - [Private endpoint health checks](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-private-endpoints.html) # Records and hosted zones (/docs/edge/route53-records-zones) ## Records [#records] A **record** says how to route traffic for a name. Each record has: - **Name:** the domain or subdomain, such as `example.com` or `api.example.com`. - **Type:** such as `A` or `AAAA`. - **Value:** what the name points to, such as `12.34.56.78`. - **Routing policy:** how Route 53 chooses an answer (see [routing policies](/docs/edge/route53-routing-policies)). - **TTL:** how long resolvers may cache the answer. ### Record types [#record-types] Know these four well: - **A:** maps a name to an **IPv4** address. - **AAAA:** maps a name to an **IPv6** address. - **CNAME:** maps a name to **another name**, whose own A or AAAA record gives the address. You **can't** create a CNAME at the top of a domain (the **zone apex**): you can for `www.example.com`, not for `example.com`. See [CNAME vs alias](/docs/edge/route53-alias). - **NS:** the **name servers** for the hosted zone: the servers that answer for the domain and so control how its traffic is routed. Route 53 also supports CAA, DS, HTTPS, MX (mail servers), NAPTR, PTR, SOA, SPF, SRV, SSHFP, SVCB, TLSA and TXT (often used to prove you own a domain). ## Hosted zones [#hosted-zones] A **[hosted zone](/docs/glossary#term-hosted-zone)** is a container for the records of a domain and its subdomains.
![A public hosted zone answers anyone on the internet, for example shop.example.com resolves to a public load balancer; a private hosted zone answers only inside the VPCs associated with it, for example db.company.internal resolves to the private IP address of an RDS database](/diagrams/edge-hosted-zones.light.svg) ![A public hosted zone answers anyone on the internet, for example shop.example.com resolves to a public load balancer; a private hosted zone answers only inside the VPCs associated with it, for example db.company.internal resolves to the private IP address of an RDS database](/diagrams/edge-hosted-zones.dark.svg)
Public names for the internet, private names for your VPCs.
- **Public hosted zones** hold records for routing traffic **on the internet**, for public names like `application1.mypublicdomain.com`. Anyone can query them. Answers can point to S3 websites, CloudFront, public EC2 instances or load balancers. - **[Private hosted zones](/docs/glossary#term-private-hosted-zone)** hold records for routing traffic **inside one or more VPCs** you associate with the zone, for private names like `db.company.internal`. Only resources in those VPCs get answers. They usually point to private IP addresses: internal web servers, databases, internal load balancers. For private hosted zones, the VPC must have the **DNS hostnames** and **DNS resolution** settings turned on. **Pricing:** $0.50 per hosted zone per month (for the first 25), plus a small charge per million queries for public zones. Queries to private zones are free, and a zone deleted within 12 hours of creation isn't charged. ## TTL (time to live) [#ttl-time-to-live] A client asks Route 53 for `myapp.example.com` and gets `A 12.34.56.78` with a TTL of 300 seconds. For the next five minutes it uses the cached address without asking again. Only after the TTL runs out does it ask Route 53 for a fresh answer. - **High TTL** (for example 24 hours): less traffic to Route 53 and lower cost, but clients may keep using **outdated** records for a long time after a change. - **Low TTL** (for example 60 seconds): more queries (**more cost**), but changes reach clients quickly, so records are easy to change. - A common trick: **lower the TTL** a day before a planned change, make the change, then raise it again. - A TTL is **required** on every record, **except alias records**, which use the TTL of the AWS resource they point to. ## Exam tips [#exam-tips] - **"Map a name to IPv4"** → A. **"IPv6"** → AAAA. **"Name to another name"** → CNAME. **"Who answers for this domain"** → NS. - **"Internal DNS names for resources in a VPC"** → private hosted zone (with DNS hostnames and resolution on). - **"Clients still go to the old IP address after a change"** → the TTL is too high; lower it before changes. - **"Reduce Route 53 query costs"** → raise the TTL (or use alias records to AWS resources, which are free). ## Common traps [#common-traps] - **"Create a CNAME for example.com."** Not allowed at the zone apex; use an alias. - **"A private hosted zone works on the internet."** Only inside associated VPCs. - **"Lower TTL means lower cost."** It means more queries and higher cost. ## Hands-on lab: a private hosted zone [#hands-on-lab-a-private-hosted-zone] **Goal:** create a private hosted zone with one record and resolve it from an EC2 instance, with no domain to buy. A hosted zone deleted within 12 hours is free; you only pay for the EC2 instance you test from (about $0.01). Any Region works. **Before you start:** you need `saa-web` (or any instance) in the default VPC, from the [EC2 basics lab](/docs/compute/ec2-basics). ### Create the zone [#create-the-zone] **Route 53 → Hosted zones → Create hosted zone**. Domain name `saa.internal`, type **Private hosted zone**, associate the **default VPC** in your Region. Create. Route 53 adds the NS and SOA records itself. ### Add a record [#add-a-record] **Create record**: name `web`, type **A**, value the **private IP** of `saa-web`, TTL 60. Create. ### Resolve it [#resolve-it] Connect to `saa-web` with EC2 Instance Connect and run: ```bash dig web.saa.internal ``` The answer section shows `web.saa.internal. 60 IN A `. From CloudShell (outside the VPC) the same name doesn't resolve. **Expected result:** an internal DNS name that only works inside your VPC. **Clean up:** delete the `web` record, then the hosted zone (within 12 hours to avoid the monthly charge). ## AWS documentation [#aws-documentation] - [Supported DNS record types](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html) - [Working with hosted zones](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-working-with.html) - [Working with private hosted zones](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html) - [Amazon Route 53 pricing](https://aws.amazon.com/route53/pricing/) # Registrar and hybrid DNS (/docs/edge/route53-registrar-hybrid-dns) ## Registrar vs DNS service [#registrar-vs-dns-service] - A **domain registrar** is where you **buy** a domain name, usually for a yearly fee: GoDaddy, Amazon Registrar (through Route 53), and others. - The registrar usually gives you a **DNS service** to manage the domain's records too. - But you can use **another DNS service**. For example, buy the domain from GoDaddy and manage its records in Route 53. **Domain registrar ≠ DNS service**, although every registrar usually comes with some DNS features. ## A third-party registrar with Route 53 [#a-third-party-registrar-with-route-53]
![Using a third-party registrar with Route 53: you buy the domain at a registrar such as GoDaddy and set its NS records to the Route 53 name servers of your public hosted zone, where you manage the records](/diagrams/edge-registrar.light.svg) ![Using a third-party registrar with Route 53: you buy the domain at a registrar such as GoDaddy and set its NS records to the Route 53 name servers of your public hosted zone, where you manage the records](/diagrams/edge-registrar.dark.svg)
Buy the name in one place, manage it in another.
If you bought your domain from another registrar, you can still use Route 53 as its DNS service: 1. Create a **public hosted zone** in Route 53 for the domain. Route 53 assigns it four **name servers**. 2. At the third-party registrar, change the domain's **name servers (NS records)** to the four Route 53 name servers. From then on, DNS queries for the domain are answered by Route 53. When you register a domain *with* Route 53, it creates the hosted zone and sets this up for you. ## Hybrid DNS [#hybrid-dns] By default, every VPC has a **Route 53 Resolver** (now named **Route 53 VPC Resolver**), at the VPC's base address plus two. It automatically answers DNS queries from your instances for: - local names for EC2 instances; - records in **private hosted zones** associated with the VPC; - public names, by asking public name servers. **Hybrid DNS** means resolving names **between your VPC and your other networks**, such as a peered VPC or an **on-premises** network connected with **Direct Connect** or **Site-to-Site VPN**. On-premises servers can't use the VPC's Resolver directly, and the VPC's Resolver doesn't know your on-premises names. **Resolver endpoints** fix both directions. ### Resolver endpoints [#resolver-endpoints]
![Route 53 Resolver endpoints: on-premises DNS servers send queries for names in AWS through an inbound endpoint to the VPC Resolver; the VPC Resolver uses a forwarding rule to send queries for on-premises names through an outbound endpoint to the on-premises DNS servers; both run over VPN or Direct Connect](/diagrams/edge-resolver-endpoints.light.svg) ![Route 53 Resolver endpoints: on-premises DNS servers send queries for names in AWS through an inbound endpoint to the VPC Resolver; the VPC Resolver uses a forwarding rule to send queries for on-premises names through an outbound endpoint to the on-premises DNS servers; both run over VPN or Direct Connect](/diagrams/edge-resolver-endpoints.dark.svg)
Inbound brings queries in; outbound sends them out.
- **[Inbound endpoint](/docs/glossary#term-resolver-endpoint):** lets **your DNS resolvers** (on-premises) resolve names **in AWS**: EC2 instances and records in private hosted zones, such as `app.aws.private`. On-premises DNS servers forward those queries to the endpoint's IP addresses. - **Outbound endpoint:** lets the **VPC Resolver** forward queries to **your DNS resolvers**, using **forwarding rules** that name the domains to forward, such as `onprem.private`. An EC2 instance can then resolve `web.onprem.private`. - Endpoints are network interfaces in your subnets (in at least two AZs for availability). Rules can be **shared with other accounts** through AWS RAM. ### Route 53 Resolver DNS Firewall [#route-53-resolver-dns-firewall] **DNS Firewall** filters the DNS queries your VPC's instances make, allowing or **blocking domains** from lists you manage or AWS provides. Its main use is stopping **DNS exfiltration**, where malware on a compromised instance sends data out by looking up names in a domain the attacker controls. ## Real-world examples [#real-world-examples] - **A start-up** registered `startup.io` at another registrar years ago. It creates a Route 53 hosted zone and updates the name servers at the registrar, to use Route 53 routing policies and alias records. - **A bank** runs Active Directory DNS on premises. With an **outbound endpoint** and a rule for `corp.bank.local`, its EC2 instances resolve on-premises names; an **inbound endpoint** lets its branch servers resolve `*.aws.bank.local` private hosted zone names. ## Exam tips [#exam-tips] - **"Domain bought from another registrar, use Route 53"** → create a public hosted zone and update the NS records at the registrar. - **"On-premises servers must resolve private hosted zone names"** → Resolver **inbound** endpoint. - **"EC2 instances must resolve on-premises domain names"** → Resolver **outbound** endpoint + forwarding rule. - **"Block instances from resolving malicious domains", "DNS exfiltration"** → Route 53 Resolver DNS Firewall. ## Common traps [#common-traps] - **"You must transfer the domain to Route 53 to use it as DNS."** Updating the NS records is enough. - **"Inbound and outbound are about internet traffic."** They're about DNS queries into and out of the VPC. - **"On-premises servers can query the VPC+2 address directly."** AWS doesn't support that; use an inbound endpoint. ## Check yourself [#check-yourself] Resolver endpoints need an on-premises network or a second VPC, and cost about $0.125 an hour per network interface, so instead: Create a Route 53 Resolver inbound endpoint in the VPC, and configure the on-premises DNS servers to forward `prod.internal` queries to the endpoint's IP addresses. Create a Resolver outbound endpoint and a forwarding rule for `corp.example` pointing to the on-premises DNS servers, and associate the rule with the VPC. ## AWS documentation [#aws-documentation] - [Registering and managing domains using Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-register.html) - [Making Amazon Route 53 the DNS service for an existing domain](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/MigratingDNS.html) - [What is Route 53 VPC Resolver?](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver.html) - [Resolving DNS queries between VPCs and your network](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-overview-DSN-queries-to-vpc.html) - [Route 53 Resolver DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall.html) # Routing policies (/docs/edge/route53-routing-policies) ## What it is [#what-it-is] A **[routing policy](/docs/glossary#term-routing-policy)** decides how Route 53 **answers** a DNS query when a name has several possible values. Don't be confused by the word *routing*. It isn't like load balancer routing, which moves the traffic. **DNS doesn't route any traffic**: it only answers the query, and the client then connects to the address it was given.
![The eight Route 53 routing policies: simple, weighted, latency, failover, geolocation, geoproximity, IP-based and multivalue answer](/diagrams/edge-routing-policies.light.svg) ![The eight Route 53 routing policies: simple, weighted, latency, failover, geolocation, geoproximity, IP-based and multivalue answer](/diagrams/edge-routing-policies.dark.svg)
Eight ways to choose an answer.
## Simple [#simple] - Usually sends traffic to **a single resource**. - One record can hold **several values** (for example three IP addresses). Route 53 returns **all of them in random order**, and the **client** picks one. - With an **alias**, you can name only **one** AWS resource. - **No health checks.** ## Weighted [#weighted]
![Weighted routing: three records with the same name have weights 70, 20 and 10, so Route 53 returns them in 70, 20 and 10 percent of answers](/diagrams/edge-weighted.light.svg) ![Weighted routing: three records with the same name have weights 70, 20 and 10, so Route 53 returns them in 70, 20 and 10 percent of answers](/diagrams/edge-weighted.dark.svg)
Split answers by relative weight.
- Controls the **percentage** of answers that go to each resource. - Each record gets a **relative weight** (0 to 255): a record's share = its weight ÷ the sum of all weights. The weights don't need to add up to 100. - All the records must have the **same name and type**. - Can be linked to **health checks**. - A weight of **0** stops traffic to that record. If **all** records have weight 0, they're returned equally. - **Use cases:** load balancing between Regions, **testing a new version** of an app on a small share of users (canary), moving traffic gradually. ## Latency-based [#latency-based] - Sends users to the resource with the **lowest latency** for them. - Latency is measured **between users and AWS Regions**: you tag each record with the Region the resource is in. Users in Germany might be sent to the US if that's faster for them. - Can be linked to **health checks**, which gives it a failover ability. - **Use case:** a global app in several Regions where speed matters most. ## Failover (active-passive) [#failover-active-passive]
![Failover routing: Route 53 answers with the primary resource while its health check passes, and with the secondary disaster recovery resource when the primary is unhealthy](/diagrams/edge-failover.light.svg) ![Failover routing: Route 53 answers with the primary resource while its health check passes, and with the secondary disaster recovery resource when the primary is unhealthy](/diagrams/edge-failover.dark.svg)
Primary while healthy, secondary when not.
- One **primary** record and one **secondary** record. - The primary must have a **[health check](/docs/edge/route53-health-checks)**. While it's healthy, Route 53 answers with the primary; when it fails, Route 53 answers with the secondary (for example a disaster recovery site). - Works in public and private hosted zones. ## Geolocation [#geolocation] - Routes by **where the user is**, not by latency. - You choose locations by **continent**, **country** or **US state**. If locations overlap, the **most precise** one wins (a record for Canada beats one for North America). - Create a **default** record for users who match no location (and for IP addresses Route 53 can't place). - Can be linked to **health checks**. - **Use cases:** website **localization** (French site for France), **restricting content** to certain countries, load balancing by region. ## Geoproximity [#geoproximity]
![Geoproximity bias: with bias 0 on both Regions, users are split at the halfway line between us-west-1 and us-east-1; with a bias of +50 on us-east-1 the line moves west, so us-east-1 serves a larger area](/diagrams/edge-geoproximity.light.svg) ![Geoproximity bias: with bias 0 on both Regions, users are split at the halfway line between us-west-1 and us-east-1; with a bias of +50 on us-east-1 the line moves west, so us-east-1 serves a larger area](/diagrams/edge-geoproximity.dark.svg)
A bias moves the boundary between two resources.
- Routes by the **location of users and of resources**: each user goes to the nearest resource. - A **bias** shifts more or less traffic to a resource by growing or shrinking its area: - **1 to 99** expands it (more traffic); - **−1 to −99** shrinks it (less traffic). - Resources can be **AWS resources** (give the AWS Region, or Local Zone group) or **non-AWS resources** (give latitude and longitude). The slides say geoproximity requires **Route 53 Traffic Flow**, a visual editor for complex routing trees. You can now create geoproximity records directly in the console; Traffic Flow is still where you see them on a map. On the exam, "shift traffic between Regions with a bias" still means geoproximity. ## IP-based [#ip-based] - Routes by the **client's IP address**. - You upload a **CIDR collection**: lists of IP ranges, each mapped to a location name. Records then say which endpoint serves each location. For example, `203.0.113.0/24` → location-1 → `1.2.3.4`. - **Use cases:** send users of a particular **ISP** to a specific endpoint, to **optimize performance or reduce network costs**. ## Multivalue answer [#multivalue-answer] - Use when routing traffic to **several resources**. - Route 53 returns **up to 8 healthy records** for each query, chosen at random. - Can be linked to **health checks**, so only healthy values are returned. That's the difference from *simple* with several values. - **Not a substitute for a load balancer**: the client still picks one address, and there's no real load spreading. The AWS documentation now also lists an **AZ-affinity** routing policy, newer than the course. New features need to be available for at least three months before they can be tested (see [how current is the exam](/docs/exam-guide#how-current-is-the-exam)), so concentrate on the eight above. ## Exam tips [#exam-tips] - **"Send 10% of users to the new version"**, **"gradual migration"** → weighted. - **"Best performance for users worldwide", "lowest latency"** → latency-based. - **"Active-passive", "disaster recovery site when the primary fails"** → failover (with a health check). - **"Users in a country must see a localized site", "restrict by country", "legal requirements"** → geolocation. - **"Shift more traffic to one Region based on distance"**, **"bias"** → geoproximity. - **"Route users of a specific ISP or IP range"** → IP-based. - **"Return several healthy IP addresses"** → multivalue answer. - **"Health checks with one record holding several IPs"** → not possible with simple; use multivalue. ## Common traps [#common-traps] - **"Latency-based sends users to the geographically closest Region."** It uses measured latency, which isn't always the closest. - **"Geolocation is the same as latency."** Geolocation uses the user's location, regardless of speed. - **"Multivalue replaces an ELB."** It doesn't. - **"Forget the default record in geolocation."** Users outside every location get no answer. ## Hands-on lab: weighted records [#hands-on-lab-weighted-records] **Goal:** create two weighted records and watch Route 53 alternate its answers. A private hosted zone deleted within 12 hours is free; testing from `saa-web` costs about $0.01. Any Region works. **Before you start:** create the `saa.internal` private hosted zone from the [records lab](/docs/edge/route53-records-zones#hands-on-lab-a-private-hosted-zone). ### Create two weighted records [#create-two-weighted-records] **Create record** in `saa.internal`: name `app`, type A, value `10.0.0.1`, TTL **5**, routing policy **Weighted**, weight **70**, record ID `blue`. Add another: same name and type, value `10.0.0.2`, weight **30**, record ID `green`. ### Ask many times [#ask-many-times] From `saa-web`: ```bash for i in $(seq 20); do dig +short app.saa.internal; sleep 6; done | sort | uniq -c ``` Roughly 14 answers are `10.0.0.1` and 6 are `10.0.0.2`. ### Stop traffic to one [#stop-traffic-to-one] Edit `green` and set its weight to **0**. Run the loop again: only `10.0.0.1` comes back. **Expected result:** answers split roughly 70/30, then all to one record when the other's weight is 0. **Clean up:** delete both records and the hosted zone. ## AWS documentation [#aws-documentation] - [Choosing a routing policy](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html) - [Weighted routing](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-weighted.html) - [Geolocation routing](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-geo.html) - [Geoproximity routing](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-geoproximity.html) - [IP-based routing](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-ipbased.html) - [Multivalue answer routing](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-multivalue.html) # The SAA-C03 exam (/docs/exam-guide) ## What the exam tests [#what-the-exam-tests] The SAA-C03 exam checks whether you can **design** solutions on AWS that follow the [AWS Well-Architected Framework](https://docs.aws.amazon.com/wellarchitected/latest/framework/welcome.html). In practice, most questions describe a company, its problem and a few constraints (cost, speed, security, effort), then ask for the best design. AWS aims the exam at people with about a year of hands-on experience. You can make up for that with the labs in this handbook: doing each one teaches you how the services behave, which is what the scenario questions test. ## Format and scoring [#format-and-scoring] | Item | Detail | | --- | --- | | Questions | 65: 50 scored, 15 unscored (you can't tell which) | | Time | 130 minutes | | Passing score | 720 out of 1,000 | | Price | 150 USD | | Valid for | 3 years | - **Two question types.** *Multiple choice* has one right answer out of four. *Multiple response* has two or more right answers out of five or more. - **Answer every question.** There's no penalty for guessing, and a blank answer counts as wrong. - **You pass overall, not per domain.** The scoring is compensatory: a strong domain makes up for a weak one. - **Where:** a Pearson VUE test centre, or online with a remote proctor. - **Short names:** questions say *Amazon SNS*, not *Amazon Simple Notification Service*. The exam's Help screen lists the full names. - **Exam day:** booking, timing, results and retakes are on the [Exam Prep](/docs/exam-prep#how-the-exam-works) page. Wrong answers (AWS calls them *distractors*) are written to look right to someone with incomplete knowledge. They often name a real service that solves a *different* problem. When two answers both work, the question's constraint decides: "least operational overhead", "most cost-effective", "fastest to implement". ## The four domains [#the-four-domains]
![SAA-C03 domain weights: Secure 30%, Resilient 26%, High-Performing 24%, Cost-Optimized 20%](/diagrams/exam-domain-weights.light.svg) ![SAA-C03 domain weights: Secure 30%, Resilient 26%, High-Performing 24%, Cost-Optimized 20%](/diagrams/exam-domain-weights.dark.svg)
Share of scored questions per domain.
Security is the biggest domain at 30%, about 15 of the 50 scored questions. Resilience is next at 26%, then performance at 24% and cost at 20%. Many questions touch two domains at once, such as "the most cost-effective *highly available* design". Each domain is split into task statements. Below, each task is summed up with the groups of notes that cover it. Group links are added as each group is written. ### Domain 1: Design Secure Architectures [#domain-1-design-secure-architectures] **1.1 Secure access to AWS resources** - IAM users, groups, roles and policies; the root user and MFA; STS and cross-account roles; resource policies. - Many accounts: Organizations, SCPs, Control Tower; Identity Center and directory federation. - The global infrastructure and the shared responsibility model. - *Notes:* [Identity & Access](/docs/identity), [Cloud Foundations](/docs/foundations). **1.2 Secure workloads and applications** - Security groups, network ACLs, route tables, NAT gateways; public and private subnets. - VPN and Direct Connect for links to and from AWS. - Shield, WAF, Secrets Manager, Cognito, GuardDuty, Macie; threats such as DDoS and SQL injection. - *Notes:* [Networking: Amazon VPC](/docs/vpc) ([NACLs](/docs/vpc/nacl-vs-security-groups), [endpoints](/docs/vpc/vpc-endpoints-privatelink), [Network Firewall](/docs/vpc/network-firewall)), [Security groups](/docs/compute/security-groups), [Security & Encryption](/docs/security) ([WAF and Shield](/docs/security/waf-shield-firewall-manager), [GuardDuty](/docs/security/guardduty-inspector-macie)), [Identity & Access](/docs/identity). **1.3 Data security controls** - Encryption at rest (KMS) and in transit (ACM, TLS); key policies and rotation. - Backups and replication; data lifecycle, retention and classification; compliance. - *Notes:* [Security & Encryption](/docs/security) ([KMS](/docs/security/kms), [Secrets Manager](/docs/security/secrets-manager), [ACM](/docs/security/acm)), [EBS encryption](/docs/storage/ebs-encryption), [EBS snapshots](/docs/storage/ebs-snapshots), [Amazon S3](/docs/s3) ([encryption](/docs/s3/encryption), [Object Lock](/docs/s3/object-lock-vault-lock), [replication](/docs/s3/versioning-replication#replication)), [Disaster Recovery & Backup](/docs/dr) ([AWS Backup](/docs/dr/aws-backup)). ### Domain 2: Design Resilient Architectures [#domain-2-design-resilient-architectures] **2.1 Scalable, loosely coupled architectures** - API Gateway; SQS, SNS, EventBridge, Step Functions; event-driven and microservice designs. - Stateless vs stateful; horizontal vs vertical scaling; caching; CDNs. - Containers (ECS, EKS, Fargate), Lambda, read replicas, storage types. - *Notes:* [Application Integration](/docs/integration) ([SQS](/docs/integration/sqs), [SNS](/docs/integration/sns), [EventBridge](/docs/integration/eventbridge), [Step Functions](/docs/integration/step-functions)), [Serverless](/docs/serverless) ([Lambda](/docs/serverless/lambda), [API Gateway](/docs/serverless/api-gateway)), [Containers](/docs/containers) ([ECS](/docs/containers/ecs), [EKS](/docs/containers/eks)), [Load Balancing & Auto Scaling](/docs/scaling), [read replicas](/docs/databases/rds-read-replicas-multi-az), [Architecture Patterns](/docs/architecture). **2.2 Highly available and fault-tolerant architectures** - AZs, Regions and Route 53; failover; DR strategies with RPO and RTO. - Immutable infrastructure; RDS Proxy; durability and replication; [X-Ray](/docs/management/x-ray). - Service quotas and throttling, including in a standby environment. - *Notes:* [Disaster Recovery & Backup](/docs/dr) ([DR strategies](/docs/dr/dr-strategies)), [DNS & Content Delivery](/docs/edge) ([failover routing](/docs/edge/route53-routing-policies#failover-active-passive), [health checks](/docs/edge/route53-health-checks)), [Databases](/docs/databases) ([RDS Proxy](/docs/databases/rds-security-proxy#rds-proxy), [Multi-AZ](/docs/databases/rds-read-replicas-multi-az#multi-az)), [Service quotas](/docs/foundations/service-quotas), [Monitoring & Governance](/docs/management) ([CloudWatch alarms](/docs/management/cloudwatch-alarms), [X-Ray](/docs/management/x-ray)). ### Domain 3: Design High-Performing Architectures [#domain-3-design-high-performing-architectures] **3.1 Storage:** S3, EFS and EBS; object vs file vs block; hybrid storage; storage that meets performance and growth needs. *Notes:* [Storage: Block & File](/docs/storage), [Amazon S3](/docs/s3), [Migration & Transfer](/docs/migration) ([Storage Gateway](/docs/migration/storage-gateway)). **3.2 Compute:** EC2 instance types, Auto Scaling, Batch, EMR, Fargate, Lambda memory sizing; decoupling; scaling metrics. *Notes:* [Compute](/docs/compute), [Load Balancing & Auto Scaling](/docs/scaling), [Serverless](/docs/serverless) ([Lambda limits](/docs/serverless/lambda-limits-concurrency)), [Containers](/docs/containers) ([Fargate](/docs/containers/ecs#fargate-launch-type)), [Analytics](/docs/analytics) ([EMR](/docs/analytics/emr)). **3.3 Databases:** engines and types (relational, key-value, in-memory, serverless); capacity planning; read replicas; RDS Proxy; ElastiCache. *Notes:* [Databases](/docs/databases). **3.4 Networking:** CloudFront and Global Accelerator; subnet tiers, routing and IP addressing; choosing a load balancer; VPN, Direct Connect, PrivateLink. *Notes:* [Networking: Amazon VPC](/docs/vpc) ([subnets](/docs/vpc/vpc-and-subnets), [VPN](/docs/vpc/site-to-site-vpn), [Direct Connect](/docs/vpc/direct-connect), [PrivateLink](/docs/vpc/vpc-endpoints-privatelink)), [DNS & Content Delivery](/docs/edge) ([CloudFront](/docs/edge/cloudfront), [Global Accelerator](/docs/edge/global-accelerator)), [Load Balancing & Auto Scaling](/docs/scaling). **3.5 Data ingestion and transformation:** Athena, Lake Formation, QuickSight; Kinesis; Glue; DataSync and Storage Gateway; data lakes; EMR; CSV to Parquet. *Notes:* [Analytics](/docs/analytics) ([Athena](/docs/analytics/athena), [Glue](/docs/analytics/glue), [Lake Formation](/docs/analytics/lake-formation), [QuickSight](/docs/analytics/quicksight), [EMR](/docs/analytics/emr)), [Application Integration](/docs/integration) ([Kinesis and Firehose](/docs/integration/kinesis)), [Migration & Transfer](/docs/migration) ([DataSync](/docs/migration/datasync), [Storage Gateway](/docs/migration/storage-gateway)). ### Domain 4: Design Cost-Optimized Architectures [#domain-4-design-cost-optimized-architectures] **4.1 Storage costs:** S3 storage classes and lifecycle; Requester Pays; EBS volume types; FSx and EFS; backup strategy; the cheapest way to move data in. *Notes:* [Amazon S3](/docs/s3) ([storage classes](/docs/s3/storage-classes), [lifecycle rules](/docs/s3/lifecycle-rules), [Requester Pays](/docs/s3/requester-pays)), [Storage: Block & File](/docs/storage), [Migration & Transfer](/docs/migration) ([large data transfers](/docs/migration/large-data-transfer)), [Cost Management](/docs/cost). **4.2 Compute costs:** On-Demand, Reserved, Savings Plans, Spot; instance families and sizes; ALB vs NLB vs GWLB; hibernation; Outposts and Snowball Edge; Lambda vs EC2 vs Fargate. *Notes:* [Compute](/docs/compute), [Load Balancing & Auto Scaling](/docs/scaling), [Serverless](/docs/serverless) ([Lambda pricing](/docs/serverless/lambda#pricing)), [Cost Management](/docs/cost). **4.3 Database costs:** DynamoDB vs RDS; serverless options; capacity units; snapshot and retention policies; MySQL vs PostgreSQL; time-series and columnar formats; schema migration. *Notes:* [Databases](/docs/databases), [Migration & Transfer](/docs/migration) ([DMS and SCT](/docs/migration/dms-sct)). **4.4 Network costs:** NAT gateway vs NAT instance, shared or one per AZ; Direct Connect vs VPN vs internet; transfer between AZs and Regions; VPC endpoints; Transit Gateway vs peering; CDNs; throttling. *Notes:* [Networking: Amazon VPC](/docs/vpc) ([networking costs](/docs/vpc/networking-costs), [NAT gateways](/docs/vpc/nat-instance-nat-gateway), [Transit Gateway](/docs/vpc/transit-gateway)), [DNS & Content Delivery](/docs/edge), [Cost Management](/docs/cost). Every domain also lists the cost tools: AWS Cost Explorer, AWS Budgets, the Cost and Usage Report, cost allocation tags and consolidated billing. They're in the [Cost Management](/docs/cost) group. ## What the course doesn't cover [#what-the-course-doesnt-cover] The course covers nearly all of the exam. These topics are in the exam guide but missing from the slides, or only named there. The notes add them from the AWS documentation, in the group shown: - **Cloud Foundations:** the [shared responsibility model](/docs/foundations/shared-responsibility), [service quotas and throttling](/docs/foundations/service-quotas), [Local Zones and Wavelength Zones](/docs/foundations/global-infrastructure#local-zones-and-wavelength-zones). - **[Identity & Access](/docs/identity):** [AWS STS, role switching and cross-account access](/docs/identity/roles-and-sts) in depth; [AWS Resource Access Manager (RAM)](/docs/identity/ram). - **[Compute](/docs/compute):** [AWS Compute Optimizer](/docs/compute/compute-optimizer); [Local Zones and Wavelength for compute](/docs/compute/hybrid-edge-compute). - **[Load Balancing & Auto Scaling](/docs/scaling):** [warm pools](/docs/scaling/scaling-policies#warm-pools), [instance refresh](/docs/scaling/scaling-policies#instance-refresh), and [AWS Auto Scaling](/docs/scaling/scaling-policies#aws-auto-scaling-and-application-auto-scaling) (scaling plans). - **[Containers](/docs/containers):** [ECS Anywhere, EKS Anywhere and EKS Distro](/docs/containers/eks#running-containers-outside-aws-regions). - **[Serverless](/docs/serverless):** [AWS Serverless Application Repository](/docs/serverless/serverless-application-repository), [AWS Device Farm](/docs/serverless/amplify#aws-device-farm). - **[Analytics](/docs/analytics):** [AWS Data Exchange, AWS Data Pipeline and Kinesis Video Streams](/docs/analytics/data-exchange-data-pipeline). - **[Monitoring & Governance](/docs/management):** [AWS X-Ray](/docs/management/x-ray), [AWS Health Dashboard](/docs/management/health-dashboard), [Service Catalog, Proton and License Manager](/docs/management/service-catalog-proton-license-manager), [Managed Grafana and Managed Service for Prometheus](/docs/management/managed-grafana-prometheus). - **[Security & Encryption](/docs/security):** [Amazon Detective, AWS Security Hub and AWS Artifact](/docs/security/detective-security-hub-artifact). - **[Networking: Amazon VPC](/docs/vpc):** [AWS Client VPN](/docs/vpc/site-to-site-vpn#aws-client-vpn). - **[Migration & Transfer](/docs/migration):** [migration strategies (the 7 Rs)](/docs/migration#the-7-rs-of-migration). - **[Cost Management](/docs/cost):** [AWS Budgets, the Cost and Usage Report and cost allocation tags](/docs/cost/budgets-cur-tags). - **Architecture Patterns:** [immutable infrastructure](/docs/architecture/immutable-infrastructure). It also works the other way. The course covers a few services the current in-scope list doesn't name: Amazon Timestream, Amazon SES, Amazon Pinpoint, Amazon Kendra, Amazon Connect, AWS Migration Hub and AWS Trusted Advisor. Amazon Personalize is on the **out-of-scope** list. The notes still cover them, marked with a *Not on the exam list* box. These notes use the online exam guide (version 1.1, 29 October 2026). An older PDF of the guide still lists Amazon Kendra, Amazon Forecast, Amazon Fraud Detector, Amazon QLDB, AWS AppSync, Amazon Pinpoint, AWS Trusted Advisor, AWS Migration Hub and AWS Audit Manager as in scope. The online list has dropped them, and version 1.1 also removed Amazon Elastic Transcoder. ## Out of scope [#out-of-scope] AWS lists services that won't be tested. The most useful ones to know, because they show up as wrong answers or in other courses: - **Developer tools:** AWS CDK, CloudShell, CodeArtifact, CodeBuild, CodeCommit, CodeDeploy, Fault Injection Service, the AWS SDKs and tools. - **Compute:** Amazon Lightsail. - **Machine learning:** Amazon Personalize, deep learning AMIs and containers, AWS Inferentia, HealthLake. - **Media:** the AWS Elemental services, Amazon IVS. - **Other:** all IoT services, Amazon MWAA, Amazon Location Service, GameLift, AWS Cloud Map, Migration Evaluator, Amazon Braket, AWS Ground Station. Out of scope means there won't be a question *about* the service. You still use the AWS CLI and CloudShell in the labs. ## How current is the exam? [#how-current-is-the-exam] AWS keeps the exam in step with how AWS works today. The [AWS Certification FAQ](https://aws.amazon.com/certification/faqs/) says: - **When a service or feature changes,** the certification team **replaces the exam questions affected by the change**. So the current AWS documentation is the right thing to study, and that's what these notes follow. Where the course slides are out of date, an *Updated since the slides* box gives the current fact. - **A new service or feature** must be generally available for **3 months** before it can appear on any exam. Very new features may not be tested yet, but learning them never makes an older answer right. - **Questions rotate** in and out of the exam all the time, within the exam guide. - **Exam guide revisions** are published **at least one month** before they reach the exam. The guide's *Revisions* page lists each change; version 1.1 is the current one. - **If a question seems affected by a change,** choose the best available answer from the options given. Two more things to keep in mind: - **15 of the 65 questions are unscored trial questions**, mixed in without any marking. If a question feels odd or out of date, it may well be one of them: answer it and move on. - **Practice tests from other providers** can lag behind AWS. When a practice answer disagrees with the AWS documentation, trust the documentation. Questions rarely depend on an exact limit that has recently changed. If one does, the answer options are written so that only one fits: pick the option that matches current AWS behaviour. ## AWS documentation [#aws-documentation] - [SAA-C03 exam guide](https://docs.aws.amazon.com/aws-certification/latest/solutions-architect-associate-03/solutions-architect-associate-03.html) - [In-scope AWS services](https://docs.aws.amazon.com/aws-certification/latest/solutions-architect-associate-03/saa-03-in-scope-services.html) - [Out-of-scope AWS services](https://docs.aws.amazon.com/aws-certification/latest/solutions-architect-associate-03/saa-03-out-of-scope-services.html) - [Exam guide revisions](https://docs.aws.amazon.com/aws-certification/latest/solutions-architect-associate-03/saa-03-revisions.html) - [AWS Certified Solutions Architect – Associate](https://aws.amazon.com/certification/certified-solutions-architect-associate/) - [AWS Certification FAQs](https://aws.amazon.com/certification/faqs/) # Certification paths (/docs/exam-prep/certification-paths) Nothing on this page is tested on SAA-C03. It's here to help you plan what comes next. ## The certification levels [#the-certification-levels]
![AWS Certification levels in November 2026: Business, with AI Business Strategist in beta; Foundational, with Cloud Practitioner and AI Practitioner; Associate, with Solutions Architect, Developer, CloudOps Engineer, Data Engineer and Machine Learning Engineer; Professional, with Solutions Architect, DevOps Engineer and Generative AI Developer; Specialty, with Security and Advanced Networking, which retires at the end of 2026](/diagrams/exam-cert-levels.light.svg) ![AWS Certification levels in November 2026: Business, with AI Business Strategist in beta; Foundational, with Cloud Practitioner and AI Practitioner; Associate, with Solutions Architect, Developer, CloudOps Engineer, Data Engineer and Machine Learning Engineer; Professional, with Solutions Architect, DevOps Engineer and Generative AI Developer; Specialty, with Security and Advanced Networking, which retires at the end of 2026](/diagrams/exam-cert-levels.dark.svg)
Solutions Architect Associate, in green, is where you are.
- **Foundational:** knowledge of the AWS Cloud (Cloud Practitioner) or of AI and generative AI on AWS (AI Practitioner). No prior experience needed; both are optional before an associate exam. - **Associate:** role-based exams on building and running workloads. Prior cloud or IT experience recommended. Passing score 720. - **Professional:** advanced design, modernization and automation. About 2 years of AWS experience recommended; 75 questions in 180 minutes, 300 USD, passing score 750. - **Specialty:** depth in one area, for people who advise in it. Passing score 750. - **Business:** a new level for people who drive AI adoption without needing technical skills. The line-up has changed since the course was recorded: - **SysOps Administrator – Associate** became **CloudOps Engineer – Associate** (SOA-C03) on 30 September 2025. - **Machine Learning – Specialty** was retired on 31 March 2026; **Machine Learning Engineer – Associate** and the new **Generative AI Developer – Professional** cover that ground. - **Advanced Networking – Specialty** retires on **31 December 2026**. - **AI Business Strategist** (business level) is in beta. - **Solutions Architect – Professional** and **Developer – Associate** are being updated. - AWS also offers **microcredentials**: hands-on assessments in a live AWS environment (serverless, agentic AI, application networking, incident response) that complement certifications. ## Paths by role [#paths-by-role] AWS groups the exams into paths for job roles. Foundational exams are optional at the start of each; "dive deep" exams come after. - **Solutions Architect:** Solutions Architect – Associate → Solutions Architect – Professional; dive deep with Security – Specialty. - **Application Architect:** Solutions Architect – Associate → Developer – Associate → DevOps Engineer – Professional; dive deep with Solutions Architect – Professional. - **Systems Administrator / Cloud Engineer:** CloudOps Engineer – Associate → DevOps Engineer – Professional or Security – Specialty. - **DevOps Engineer:** Developer – Associate and CloudOps Engineer – Associate → DevOps Engineer – Professional. - **Security Engineer / Security Architect:** CloudOps Engineer or Solutions Architect – Associate → Security – Specialty; dive deep with DevOps Engineer or Solutions Architect – Professional. - **Software Development Engineer:** Developer – Associate → DevOps Engineer – Professional. - **Network Engineer:** Solutions Architect – Associate → Advanced Networking – Specialty (until it retires); dive deep with Security – Specialty. - **Data Engineer:** Solutions Architect – Associate → Data Engineer – Associate; dive deep with Machine Learning Engineer – Associate or Security – Specialty. - **Machine learning and AI roles** (ML engineer, MLOps engineer, data scientist, prompt engineer): AI Practitioner → Machine Learning Engineer – Associate (often after Solutions Architect – Associate) → Generative AI Developer – Professional. ## After Solutions Architect – Associate [#after-solutions-architect--associate]
![Where to go after Solutions Architect Associate: Solutions Architect Professional for bigger, multi-account designs; Security Specialty for security roles; DevOps Engineer Professional through the Developer or CloudOps Engineer Associate; or Data Engineer and Machine Learning Engineer Associate for data and AI work](/diagrams/exam-next-steps.light.svg) ![Where to go after Solutions Architect Associate: Solutions Architect Professional for bigger, multi-account designs; Security Specialty for security roles; DevOps Engineer Professional through the Developer or CloudOps Engineer Associate; or Data Engineer and Machine Learning Engineer Associate for data and AI work](/diagrams/exam-next-steps.dark.svg)
Four common next steps.
- **Go deeper in architecture:** Solutions Architect – Professional (complex organizations, migrations, multi-account and hybrid designs). - **Specialize in security:** Security – Specialty builds directly on the IAM, KMS and VPC pages here. - **Move toward automation:** Developer or CloudOps Engineer – Associate, then DevOps Engineer – Professional. - **Move toward data and AI:** Data Engineer – Associate, Machine Learning Engineer – Associate. Your 50% voucher from passing SAA-C03 works for any of them. Keep your certification active by recertifying within 3 years (passing a higher-level exam in the same path also counts). ## Congratulations [#congratulations] You've reached the end of the notes. Good luck on the exam. Once you pass, help others: share what worked for you, and keep building on AWS. ## AWS documentation [#aws-documentation] - [AWS Certification](https://aws.amazon.com/certification/) - [AWS Certification paths](https://aws.amazon.com/certification/certification-levels/) - [Coming soon to AWS Certification](https://aws.amazon.com/certification/coming-soon/) - [Recertification](https://aws.amazon.com/certification/recertification/) # Exam Prep (/docs/exam-prep) You've been through every service and pattern on the exam. This group helps you turn that into a pass: how to study the last stretch, how to answer the questions, and what happens before, during and after the exam. ## Where you are now [#where-you-are-now] Open the [official exam page](https://aws.amazon.com/certification/certified-solutions-architect-associate/) and the [exam guide](/docs/exam-guide), and check each task statement: can you explain it and name the service for it? Mark the ones you can't and reread those pages. ## Practice makes perfect [#practice-makes-perfect] - **If you're new to AWS, get some practice before rushing to the exam.** The exam guide recommends about **one year of hands-on experience** designing on AWS; the labs in these notes are a start. - **Practice exams** show you the question style and your weak domains. AWS offers a free **Official Practice Question Set** and a full **Official Practice Exam** on AWS Skill Builder. - **Feeling overwhelmed** by everything you've learned is normal. Go through the notes **one more time**: the second pass is much faster, and the pieces start to connect. - Use the **[keyword cheat sheet](/docs/exam-prep/keyword-cheatsheet)** to test yourself: cover the answers and say them out loud. ## Answering by elimination [#answering-by-elimination]
![Answering by elimination: read all four answers and find the job and the qualifier; rule out the two that are wrong on a fact; apply the qualifier such as cost, effort or speed to the last two; pick the simplest answer with the fewest moving parts](/diagrams/exam-elimination.light.svg) ![Answering by elimination: read all four answers and find the job and the qualifier; rule out the two that are wrong on a fact; apply the qualifier such as cost, effort or speed to the last two; pick the simplest answer with the fewest moving parts](/diagrams/exam-elimination.dark.svg)
Four answers to one in three cuts.
- Most questions are **scenarios**: a company, a problem and a goal. - **Rule out the answers you know are wrong**: a service that can't do the job, a feature that doesn't exist, a step that breaks a stated constraint. - **Of the answers left, find the one that makes the most sense** for the question's qualifier: *most cost-effective*, *least operational overhead*, *highest availability*… (see [how to read a scenario question](/docs/architecture#how-to-read-a-scenario-question)). - There are **very few trick questions**. **Don't overthink it.** - **If a solution works but is very complicated, it's probably wrong.** AWS prefers the managed, simple answer. - **Multiple response** questions tell you how many answers to pick ("Choose two."). Each choice must be right on its own. ## Read beyond the notes [#read-beyond-the-notes] - **AWS whitepapers:** skim the ones that interest you. The course points to three: - *Architecting for the Cloud: AWS Best Practices* (an older paper, whose ideas now live in the Well-Architected Framework); - the [AWS Well-Architected Framework](https://docs.aws.amazon.com/wellarchitected/latest/framework/welcome.html) (see [Well-Architected](/docs/architecture/well-architected)); - [Disaster Recovery of Workloads on AWS](https://docs.aws.amazon.com/whitepapers/latest/disaster-recovery-workloads-on-aws/disaster-recovery-workloads-on-aws.html) (see [DR strategies](/docs/dr/dr-strategies)). - **Each service's FAQ** (for example the [Amazon VPC FAQs](https://aws.amazon.com/vpc/faqs/)): FAQs answer many of the questions the exam asks and confirm you understand a service. - **The community:** discuss with others in course Q&As and forums, read blogs, go to local AWS meetups, and watch **AWS re:Invent** talks on YouTube. ## How the exam works [#how-the-exam-works]
![From booking to result: prepare with practice exams, book and sit the exam of 65 questions in 130 minutes, and get the scaled score within 5 business days; 720 or more is a pass, valid for 3 years with a 50 percent voucher for the next exam, and below 720 you can retake after 14 days](/diagrams/exam-flow.light.svg) ![From booking to result: prepare with practice exams, book and sit the exam of 65 questions in 130 minutes, and get the scaled score within 5 business days; 720 or more is a pass, valid for 3 years with a 50 percent voucher for the next exam, and below 720 you can retake after 14 days](/diagrams/exam-flow.dark.svg)
From booking to badge.
**Booking** - Register and schedule from your **AWS Certification Account** (through [aws.amazon.com/certification](https://aws.amazon.com/certification/)). The exam costs **150 USD**. - Take it at a **Pearson VUE test center** or **online with a remote proctor**. - Bring the **ID documents** described in your confirmation email. - If English isn't your first language, request the **ESL +30 minutes** accommodation **once, before you register**: it gives you 30 extra minutes. **On the day** - **65 questions in 130 minutes**: about two minutes each. 15 of the questions are unscored, and you can't tell which. - **No notes, no pen** (online, nothing on your desk), and no speaking. - Use the **Flag for Review** button for questions you want to revisit, and keep moving. At the end, a review screen lists all, unanswered and flagged questions. - **Answer everything**: a blank counts as wrong, and there's no penalty for guessing. **Results** - You need a scaled score of **720 out of 1,000** to pass. - Results, with your overall score, arrive in your AWS Certification Account **within 5 business days** (often sooner). You won't see which questions you got right or wrong, only how you did per domain. - If you **fail**, you can retake after **14 days**. - If you **pass**, the certification is valid for **3 years**, and you get a **50% discount voucher** for another exam. The slides send you to `aws.training` to register. Exams are now booked from the **AWS Certification Account**, reached from the AWS Certification website. The format, price, passing score and retake wait are unchanged. ## Exam-day checklist [#exam-day-checklist] - The night before: skim the [keyword cheat sheet](/docs/exam-prep/keyword-cheatsheet), then sleep. - Online exam: test your computer and webcam beforehand, clear your desk, and launch up to 30 minutes early. - Test center: arrive 15 to 30 minutes early with your ID. - During the exam: one pass answering everything (flag the doubtful ones), then a second pass on the flags. ## AWS documentation [#aws-documentation] - [AWS Certified Solutions Architect – Associate](https://aws.amazon.com/certification/certified-solutions-architect-associate/) - [Before testing (scheduling, ID, accommodations)](https://aws.amazon.com/certification/policies/before-testing/) - [During testing](https://aws.amazon.com/certification/policies/during-testing/) - [After testing (scoring, results, retakes)](https://aws.amazon.com/certification/policies/after-testing/) - [AWS Whitepapers & Guides](https://aws.amazon.com/whitepapers/) # Keyword cheat sheet (/docs/exam-prep/keyword-cheatsheet) Exam questions hide the answer in a few words: "least operational overhead", "millions of requests per second", "without changing the application". This page collects every **keyword → answer** tip from the notes (885 of them), in the order of the sidebar. Each line links to the page that explains it. How to use it: - **Cover the right side** of each arrow and say the answer before you read it. - **Search the page** (Ctrl+F or ⌘F) for a word from a practice question, such as "decouple" or "on-premises". - When an answer surprises you, **open the linked page** rather than memorizing the line. ## Cloud Foundations [#cloud-foundations] - **"Avoid large up-front costs", "pay only for what is used"** → trade fixed expense for variable expense (on-demand pricing). ([Cloud Foundations](/docs/foundations)) - **"Unpredictable traffic", "don't want to over-provision"** → stop guessing capacity: elasticity, usually Auto Scaling. ([Cloud Foundations](/docs/foundations)) - **"Least operational overhead", "fully managed"** → the most managed option that fits, often serverless or SaaS-style services rather than EC2. ([Cloud Foundations](/docs/foundations)) - **"Must keep some systems in the company data center"** → hybrid: connect on-premises to AWS rather than moving everything. ([Cloud Foundations](/docs/foundations)) - **"Reach users worldwide with low latency"** → go global in minutes: more Regions, or edge services such as CloudFront. ([Cloud Foundations](/docs/foundations)) - **"Data must not leave the country", "data residency"** → choose a Region in that country. Compliance beats latency and price. ([Global infrastructure](/docs/foundations/global-infrastructure)) - **"Highly available", "survive a data center failure"** → spread across **multiple AZs** in one Region. ([Global infrastructure](/docs/foundations/global-infrastructure)) - **"Survive the loss of a whole Region", "disaster recovery in another geography"** → **multiple Regions**. ([Global infrastructure](/docs/foundations/global-infrastructure)) - **"Users worldwide", "reduce latency for static content"** → edge locations through **CloudFront**. ([Global infrastructure](/docs/foundations/global-infrastructure)) - **"Single-digit millisecond latency for users in a specific city"** → **Local Zones**. ([Global infrastructure](/docs/foundations/global-infrastructure)) - **"Ultra-low latency for mobile / 5G devices"** → **Wavelength Zones**. ([Global infrastructure](/docs/foundations/global-infrastructure)) - **"Run AWS services in our own data center"** → **AWS Outposts**. ([Global infrastructure](/docs/foundations/global-infrastructure)) - **"Same physical AZ across two accounts"** → compare **AZ IDs**, not AZ names. ([Global infrastructure](/docs/foundations/global-infrastructure)) - **"Who patches the guest OS on EC2?"** → the customer. ([Shared responsibility model](/docs/foundations/shared-responsibility)) - **"Who patches the OS or database engine for RDS?"** → AWS. ([Shared responsibility model](/docs/foundations/shared-responsibility)) - **"Physical security of data centers", "decommissioning disks"** → AWS. ([Shared responsibility model](/docs/foundations/shared-responsibility)) - **"Encrypting data", "IAM permissions", "security group rules"** → the customer, on every service. ([Shared responsibility model](/docs/foundations/shared-responsibility)) - **"Reduce the operational burden of security patching"** → move to a managed or serverless service (RDS, Fargate, Lambda). ([Shared responsibility model](/docs/foundations/shared-responsibility)) - **"Proof of AWS's compliance", "SOC or PCI reports"** → AWS Artifact. ([Shared responsibility model](/docs/foundations/shared-responsibility)) - **"An application on EC2 needs to call S3"** → give the instance an **IAM role**. Never store access keys on the instance. ([Console, CLI and SDK](/docs/foundations/console-cli-sdk)) - **"Developers need CLI access across many accounts"** → **IAM Identity Center** with `aws configure sso` (short-term credentials). ([Console, CLI and SDK](/docs/foundations/console-cli-sdk)) - **"Access keys were committed to a public repository"** → deactivate and delete the keys straight away, then check CloudTrail for what they were used for. ([Console, CLI and SDK](/docs/foundations/console-cli-sdk)) - **"Automate the same task repeatedly"** → CLI scripts or SDK code, or infrastructure as code (CloudFormation). ([Console, CLI and SDK](/docs/foundations/console-cli-sdk)) - **"Who can use the console?"** → anyone with a user name and password (and MFA). The CLI and SDKs need credentials, not a password. ([Console, CLI and SDK](/docs/foundations/console-cli-sdk)) - **"`ThrottlingException`", "`RequestLimitExceeded`", "429", "intermittent errors under load"** → retry with **exponential backoff and jitter**; consider a quota increase. ([Service quotas and throttling](/docs/foundations/service-quotas)) - **"Failover to the DR Region failed because instances couldn't launch"** → the DR Region's **service quotas** weren't raised in advance. ([Service quotas and throttling](/docs/foundations/service-quotas)) - **"Be notified before reaching a limit"** → a **CloudWatch alarm** on the quota's usage (from Service Quotas), or Trusted Advisor. ([Service quotas and throttling](/docs/foundations/service-quotas)) - **"New accounts in the organisation need higher limits automatically"** → **Service Quotas request templates** with AWS Organizations. ([Service quotas and throttling](/docs/foundations/service-quotas)) - **"Lambda functions are throttled during peaks"** → the concurrency quota: raise it, or use reserved or provisioned concurrency (see [Lambda concurrency](/docs/serverless/lambda-limits-concurrency#concurrency-and-throttling)). ([Service quotas and throttling](/docs/foundations/service-quotas)) ## Identity & Access [#identity--access] - **"Global service", "not tied to a Region"** → IAM (so are Organizations, Route 53 and CloudFront). ([Identity & Access](/docs/identity)) - **"Grant an EC2 instance or Lambda function access to S3 / DynamoDB"** → an IAM role, never access keys. ([Identity & Access](/docs/identity)) - **"Many accounts", "central management", "consolidated billing"** → AWS Organizations. ([Identity & Access](/docs/identity)) - **"Single sign-on for employees across accounts"** → IAM Identity Center. ([Identity & Access](/docs/identity)) - **"Hundreds of thousands of users", "mobile app users", "sign in with Google / Facebook"** → Amazon Cognito, not IAM. ([Identity & Access](/docs/identity)) - **"Give a team the same permissions"** → put the users in a **group** and attach the policy to the group. ([Users, groups and policies](/docs/identity/users-groups-policies)) - **"Least privilege"** → a customer managed policy with only the needed actions and resources. ([Users, groups and policies](/docs/identity/users-groups-policies)) - **"Policy attached directly to one user and deleted with it"** → inline policy. ([Users, groups and policies](/docs/identity/users-groups-policies)) - **"Can a group contain another group?"** → no. ([Users, groups and policies](/docs/identity/users-groups-policies)) - **"Protect the root user"** → strong password, MFA, no access keys, don't use it day to day. ([Root user, MFA and passwords](/docs/identity/mfa-password-policy)) - **"Stolen password must not be enough to sign in"** → MFA. ([Root user, MFA and passwords](/docs/identity/mfa-password-policy)) - **"Require users to use strong passwords / rotate them"** → IAM password policy. ([Root user, MFA and passwords](/docs/identity/mfa-password-policy)) - **"Only allow an action if the user signed in with MFA"** → condition `aws:MultiFactorAuthPresent`. ([Root user, MFA and passwords](/docs/identity/mfa-password-policy)) - **"Which task needs the root user?"** → account settings (email, closing the account), S3 MFA Delete, restoring a locked-out admin, Billing access for IAM users. ([Root user, MFA and passwords](/docs/identity/mfa-password-policy)) - **"An application on EC2 needs AWS credentials"** → IAM role, not access keys. ([Access keys](/docs/identity/access-keys)) - **"Access keys were exposed"** → deactivate or delete them immediately, then review activity in [CloudTrail](/docs/management/cloudtrail). ([Access keys](/docs/identity/access-keys)) - **"Rotate access keys without downtime"** → create a second key, switch over, then delete the first (two keys per user allow this). ([Access keys](/docs/identity/access-keys)) - **"Find unused or old access keys"** → IAM credential report or the key's *last used* information. ([Access keys](/docs/identity/access-keys)) - **"Access key ID ≈ user name, secret access key ≈ password"** → the way the slides frame it. ([Access keys](/docs/identity/access-keys)) - **"Give an EC2 instance / Lambda function access to an AWS service"** → an IAM role (instance profile for EC2, execution role for Lambda). ([Roles and STS](/docs/identity/roles-and-sts)) - **"Temporary credentials"** → AWS STS, usually `AssumeRole`. ([Roles and STS](/docs/identity/roles-and-sts)) - **"Users in another account need access"** → a cross-account role with a trust policy naming that account. ([Roles and STS](/docs/identity/roles-and-sts)) - **"Federated users from a corporate directory (SAML)"** → `AssumeRoleWithSAML`, or more simply IAM Identity Center. ([Roles and STS](/docs/identity/roles-and-sts)) - **"Who can assume this role?"** → the trust policy. **"What can the role do?"** → the permissions policy. ([Roles and STS](/docs/identity/roles-and-sts)) - **"List all users and the status of their passwords, MFA and access keys"** → IAM credential report. ([Security tools and best practices](/docs/identity/security-tools-best-practices)) - **"See which services a user / role has used, to remove unused permissions"** → last accessed information (Access Advisor). ([Security tools and best practices](/docs/identity/security-tools-best-practices)) - **"Find S3 buckets or roles shared with external accounts"** → IAM Access Analyzer. ([Security tools and best practices](/docs/identity/security-tools-best-practices)) - **"Generate a least-privilege policy based on actual activity"** → Access Analyzer policy generation. ([Security tools and best practices](/docs/identity/security-tools-best-practices)) - **"Only allow API calls from the corporate network"** → condition `aws:SourceIp`. ([Conditions and policy evaluation](/docs/identity/policy-conditions-evaluation)) - **"Restrict which Regions can be used"** → `aws:RequestedRegion` (in an IAM policy or, across accounts, an SCP). ([Conditions and policy evaluation](/docs/identity/policy-conditions-evaluation)) - **"Allow every account in our organization to access the bucket"** → bucket policy with `aws:PrincipalOrgID`. ([Conditions and policy evaluation](/docs/identity/policy-conditions-evaluation)) - **"Let developers create roles without being able to escalate privileges"** → permissions boundary. ([Conditions and policy evaluation](/docs/identity/policy-conditions-evaluation)) - **"Policy allows and another denies"** → explicit deny wins. ([Conditions and policy evaluation](/docs/identity/policy-conditions-evaluation)) - **"`ListBucket` doesn't work but `GetObject` does"** → wrong resource ARN level (bucket vs `bucket/*`). ([Conditions and policy evaluation](/docs/identity/policy-conditions-evaluation)) - **"Read from a resource in account A and write to a resource in account B at the same time"** → resource-based policy on the B resource. ([Roles vs resource-based policies](/docs/identity/roles-vs-resource-policies)) - **"Service doesn't support resource-based policies"** (EC2, for example) → cross-account role. ([Roles vs resource-based policies](/docs/identity/roles-vs-resource-policies)) - **"Allow EventBridge to invoke a Lambda function"** → Lambda resource-based policy. **"…to run an ECS task"** → IAM role for EventBridge. ([Roles vs resource-based policies](/docs/identity/roles-vs-resource-policies)) - **"Manage many accounts centrally", "one bill"** → AWS Organizations, consolidated billing. ([AWS Organizations and SCPs](/docs/identity/organizations-scps)) - **"Share Reserved Instance / Savings Plans discounts between accounts"** → consolidated billing in Organizations. ([AWS Organizations and SCPs](/docs/identity/organizations-scps)) - **"Prevent all users in member accounts, including admins, from using a service or Region"** → SCP. ([AWS Organizations and SCPs](/docs/identity/organizations-scps)) - **"The SCP denies it but the management account can still do it"** → SCPs don't apply to the management account. ([AWS Organizations and SCPs](/docs/identity/organizations-scps)) - **"Ensure only principals in our organization can access our resources"** → RCP, or `aws:PrincipalOrgID` in resource policies. ([AWS Organizations and SCPs](/docs/identity/organizations-scps)) - **"Enforce consistent tags"** → tag policies. ([AWS Organizations and SCPs](/docs/identity/organizations-scps)) - **"Set up a multi-account environment quickly, following best practices"** → AWS Control Tower. ([AWS Control Tower](/docs/identity/control-tower)) - **"Automatically create new accounts that comply with company standards"** → Control Tower Account Factory. ([AWS Control Tower](/docs/identity/control-tower)) - **"Preventive guardrail"** → SCP. **"Detective guardrail"** → AWS Config rule. **"Proactive"** → CloudFormation hook. ([AWS Control Tower](/docs/identity/control-tower)) - **"Monitor compliance across accounts on a dashboard"** → Control Tower. ([AWS Control Tower](/docs/identity/control-tower)) - **"Single sign-on to multiple AWS accounts"**, **"central management of workforce access"** → IAM Identity Center. ([IAM Identity Center](/docs/identity/iam-identity-center)) - **"Users already exist in Active Directory / Okta / Entra ID"** → Identity Center with that identity source. ([IAM Identity Center](/docs/identity/iam-identity-center)) - **"A collection of policies assigned to users for an account"** → permission set. ([IAM Identity Center](/docs/identity/iam-identity-center)) - **"Permissions based on user attributes such as department"** → ABAC. ([IAM Identity Center](/docs/identity/iam-identity-center)) - **"Single sign-on to business apps like Salesforce or Microsoft 365"** → Identity Center application assignments. ([IAM Identity Center](/docs/identity/iam-identity-center)) - **"Users must be managed in AWS, with a trust to on-premises AD"** → AWS Managed Microsoft AD. ([AWS Directory Service](/docs/identity/directory-service)) - **"Use existing on-premises AD users without storing them in AWS"** → AD Connector. ([AWS Directory Service](/docs/identity/directory-service)) - **"Low-cost, standalone, AD-compatible directory, no on-premises link"** → Simple AD. ([AWS Directory Service](/docs/identity/directory-service)) - **"Run AD-aware apps such as SQL Server or SharePoint on AWS"** → AWS Managed Microsoft AD. ([AWS Directory Service](/docs/identity/directory-service)) - **"Single sign-on to AWS accounts with AD users"** → IAM Identity Center connected to Managed Microsoft AD or AD Connector. ([AWS Directory Service](/docs/identity/directory-service)) - **"Share subnets / a VPC with other accounts in the organization"** → VPC sharing with AWS RAM. ([AWS RAM](/docs/identity/ram)) - **"Share a transit gateway, Resolver rules or License Manager configurations across accounts"** → AWS RAM. ([AWS RAM](/docs/identity/ram)) - **"Avoid creating duplicate resources in every account"** → share them with RAM. ([AWS RAM](/docs/identity/ram)) - **"Add sign-up and sign-in to a web or mobile app"** → Cognito user pool. ([Amazon Cognito](/docs/identity/cognito)) - **"Authenticate API Gateway requests with app users"** → Cognito user pool authorizer. ([Amazon Cognito](/docs/identity/cognito)) - **"Authenticate users at an Application Load Balancer"** → ALB with Cognito authentication. ([Amazon Cognito](/docs/identity/cognito)) - **"Mobile app users need direct access to S3 / DynamoDB"** → Cognito identity pool (temporary credentials). ([Amazon Cognito](/docs/identity/cognito)) - **"Each user can only access their own items / folder"** → identity pool + policy variable `${cognito-identity.amazonaws.com:sub}`. ([Amazon Cognito](/docs/identity/cognito)) - **"Guest access to AWS resources"** → identity pool with unauthenticated identities. ([Amazon Cognito](/docs/identity/cognito)) ## Compute [#compute] - **"Full control of the operating system"**, **"specific licensing"**, **"custom kernel"** → EC2. ([Compute](/docs/compute)) - **"Runs longer than Lambda's limit"**, **"needs a GPU"**, **"any runtime in a Docker image"** → Batch, ECS or EC2, not Lambda. ([Compute](/docs/compute)) - **"Lowest cost for fault-tolerant work"** → Spot Instances, often through Batch or an Auto Scaling group. ([Compute](/docs/compute)) - **"Bootstrap instances at launch"**, **"install software when the instance starts"** → user data. ([EC2 basics](/docs/compute/ec2-basics)) - **"Pay only while running"** → stop instances you don't need; storage is still billed. ([EC2 basics](/docs/compute/ec2-basics)) - **"In-memory database", "real-time big data in memory", "large cache"** → memory optimized (R, X). ([Instance types](/docs/compute/instance-types)) - **"Batch processing", "HPC", "media transcoding", "gaming servers"** → compute optimized (C). ([Instance types](/docs/compute/instance-types)) - **"High sequential read/write on local storage", "OLTP", "data warehousing"** → storage optimized (I, D). ([Instance types](/docs/compute/instance-types)) - **"Machine learning training", "GPU"** → accelerated computing (P, G, Trn). ([Instance types](/docs/compute/instance-types)) - **"Spiky, low average CPU", "cheapest for a small website"** → burstable T instances. ([Instance types](/docs/compute/instance-types)) - **"Best price-performance"** → Graviton (`g`) types, if the software runs on Arm. ([Instance types](/docs/compute/instance-types)) - **"Instance must accept traffic only from the load balancer"** → web servers' security group references the load balancer's security group. ([Security groups](/docs/compute/security-groups)) - **"Connection times out"** → security group (or network ACL) rule missing. **"Connection refused"** → the application. ([Security groups](/docs/compute/security-groups)) - **"Allow SSH only from the company network"** → inbound rule on port 22 with the company's CIDR, not `0.0.0.0/0`. ([Security groups](/docs/compute/security-groups)) - **"Connect without opening port 22"**, **"no SSH keys"**, **"no bastion host"**, **"audit sessions"** → Session Manager. ([Connecting to EC2](/docs/compute/connecting-to-ec2)) - **"Connect to an instance with no public IP from the internet, without a bastion"** → EC2 Instance Connect Endpoint (or Session Manager). ([Connecting to EC2](/docs/compute/connecting-to-ec2)) - **"Temporary SSH key, controlled by IAM"** → EC2 Instance Connect. ([Connecting to EC2](/docs/compute/connecting-to-ec2)) - **"Steady-state", "always on", "1 or 3 years"** → Savings Plans or Reserved Instances. ([Purchasing options](/docs/compute/purchasing-options)) - **"Flexibility across instance families, Regions, or Fargate and Lambda"** → Compute Savings Plans. ([Purchasing options](/docs/compute/purchasing-options)) - **"Change instance family during the term"** → Convertible RI or Compute Savings Plan, not Standard RI. ([Purchasing options](/docs/compute/purchasing-options)) - **"Fault-tolerant", "can be interrupted", "flexible timing", "cheapest"** → Spot. ([Purchasing options](/docs/compute/purchasing-options)) - **"Short-term, unpredictable, can't be interrupted"** → On-Demand. ([Purchasing options](/docs/compute/purchasing-options)) - **"BYOL per-socket / per-core licences", "control over the physical server"** → Dedicated Hosts. ([Purchasing options](/docs/compute/purchasing-options)) - **"Hardware not shared with other AWS accounts", no licence need** → Dedicated Instances. ([Purchasing options](/docs/compute/purchasing-options)) - **"Guarantee capacity in a specific AZ"** → On-Demand Capacity Reservation (or a zonal RI). ([Purchasing options](/docs/compute/purchasing-options)) - **"Cheapest", "fault-tolerant", "can be interrupted", "flexible start and end time"** → Spot. ([Spot Instances](/docs/compute/spot-instances)) - **"2-minute warning"** → Spot interruption notice; handle it with an EventBridge rule or by checking instance metadata. ([Spot Instances](/docs/compute/spot-instances)) - **"Stop Spot Instances and stop new ones launching"** → cancel the request, then terminate the instances. ([Spot Instances](/docs/compute/spot-instances)) - **"Launch Spot across many instance types and AZs with the fewest interruptions"** → a fleet or Auto Scaling group with **price-capacity-optimized** allocation. ([Spot Instances](/docs/compute/spot-instances)) - **"Mix On-Demand for the baseline and Spot for extra capacity"** → a fleet or Auto Scaling group with mixed purchase options. ([Spot Instances](/docs/compute/spot-instances)) - **"Instance needs a fixed public IP that survives stop/start"** → Elastic IP. ([IP addressing](/docs/compute/ip-addressing)) - **"Quickly move a public IP to a standby instance"** → remap the Elastic IP. ([IP addressing](/docs/compute/ip-addressing)) - **"Public IP changed after restart"** → auto-assigned public IPs change on stop/start; use an Elastic IP, DNS or a load balancer. ([IP addressing](/docs/compute/ip-addressing)) - **"Low latency, high throughput between instances", "HPC", "tightly coupled"** → cluster placement group. ([Placement groups](/docs/compute/placement-groups)) - **"Critical instances must not share hardware", "maximise availability of a small number of instances"** → spread. ([Placement groups](/docs/compute/placement-groups)) - **"Hadoop / HDFS / Cassandra / Kafka", "large distributed workload aware of racks"** → partition. ([Placement groups](/docs/compute/placement-groups)) - **"Move a private IP (or MAC address) to a standby instance for failover"** → detach and attach a secondary ENI. ([Elastic network interfaces](/docs/compute/eni)) - **"Instance in two subnets / dual-homed"** → attach a second ENI from the other subnet (same AZ). ([Elastic network interfaces](/docs/compute/eni)) - **"Keep the in-memory state", "faster boot", "applications take a long time to warm up"** → EC2 Hibernate. ([EC2 Hibernate](/docs/compute/hibernate)) - **"Root volume must be…"** → EBS, encrypted, big enough for RAM. ([EC2 Hibernate](/docs/compute/hibernate)) - **"Launch instances faster", "pre-installed software", "reduce boot time"** → a golden AMI (plus user data for dynamic settings). ([AMIs](/docs/compute/ami)) - **"Use the same AMI in another Region"** → copy the AMI to that Region. ([AMIs](/docs/compute/ami)) - **"Share an AMI with another account"** → modify the AMI's permissions (and the KMS key policy if it's encrypted). ([AMIs](/docs/compute/ami)) - **"Automate building and patching AMIs"** → EC2 Image Builder. ([AMIs](/docs/compute/ami)) - **"Developers want to deploy code without managing infrastructure", "quickly deploy a web app"**, on a supported language → Elastic Beanstalk. ([Elastic Beanstalk](/docs/compute/elastic-beanstalk)) - **"Background jobs", "long-running tasks decoupled from the web app"** → a Beanstalk **worker** environment with SQS. ([Elastic Beanstalk](/docs/compute/elastic-beanstalk)) - **"Cheap dev environment"** → single-instance environment. **"Production, highly available"** → load-balanced environment. ([Elastic Beanstalk](/docs/compute/elastic-beanstalk)) - **"Run batch jobs at scale", "hundreds of thousands of jobs", "managed job scheduling"** → AWS Batch. ([AWS Batch](/docs/compute/batch)) - **"Job runs longer than Lambda allows", "needs a custom runtime or GPU", "needs lots of disk"** → Batch, not Lambda. ([AWS Batch](/docs/compute/batch)) - **"Reduce the cost of batch processing"** → Batch with **Spot** compute environments. ([AWS Batch](/docs/compute/batch)) - **"Run AWS services on-premises with the same APIs"**, **"data must stay in our data centre"**, **"low latency to on-premises systems"** → AWS Outposts. ([Hybrid and edge compute](/docs/compute/hybrid-edge-compute)) - **"Who handles physical security of an Outpost?"** → the customer. ([Hybrid and edge compute](/docs/compute/hybrid-edge-compute)) - **"Single-digit millisecond latency for users in a specific city"** → Local Zones. ([Hybrid and edge compute](/docs/compute/hybrid-edge-compute)) - **"Ultra-low latency for 5G mobile devices"** → Wavelength. ([Hybrid and edge compute](/docs/compute/hybrid-edge-compute)) - **"Extend or migrate a VMware vSphere data centre, keep using VMware tools"** → VMware Cloud on AWS. ([Hybrid and edge compute](/docs/compute/hybrid-edge-compute)) - **"Recommend optimal instance types / sizes based on utilisation"**, **"right-sizing"**, **"identify over-provisioned EC2 instances"** → AWS Compute Optimizer. ([AWS Compute Optimizer](/docs/compute/compute-optimizer)) - **"Recommend Lambda memory size"** or **"EBS volume type"** → Compute Optimizer too. ([AWS Compute Optimizer](/docs/compute/compute-optimizer)) - **"Include memory utilisation in recommendations"** → install the CloudWatch agent. ([AWS Compute Optimizer](/docs/compute/compute-optimizer)) ## Storage: Block & File [#storage-block--file] - **"Disk for one EC2 instance", "boot volume", "database on EC2"** → EBS. ([Storage: Block & File](/docs/storage)) - **"Shared file system for many Linux instances across AZs"** → EFS. ([Storage: Block & File](/docs/storage)) - **"Shared file system for Windows", "SMB", "Active Directory"** → FSx for Windows File Server. ([Storage: Block & File](/docs/storage)) - **"HPC", "parallel file system", "process data from S3 at high speed"** → FSx for Lustre. ([Storage: Block & File](/docs/storage)) - **"Highest IOPS, temporary data, cache"** → instance store. ([Storage: Block & File](/docs/storage)) - **"Store unlimited files, accessed over HTTP, cheaply"** → S3 (object storage). ([Storage: Block & File](/docs/storage)) - **"Persistent block storage for an EC2 instance"** → EBS. ([EBS volumes](/docs/storage/ebs-volumes)) - **"Move an EBS volume to another AZ"** → snapshot, then create a volume from it in the other AZ. ([EBS volumes](/docs/storage/ebs-volumes)) - **"Keep the root volume when the instance is terminated"** → turn off *Delete on termination* for it. ([EBS volumes](/docs/storage/ebs-volumes)) - **"Increase disk size without downtime"** → Elastic Volumes (then grow the file system). ([EBS volumes](/docs/storage/ebs-volumes)) - **"Back up EBS volumes"**, **"automate snapshots on a schedule"** → EBS snapshots with Data Lifecycle Manager or AWS Backup. ([EBS snapshots](/docs/storage/ebs-snapshots)) - **"Move an EBS volume to another AZ / Region"** → snapshot (copy it for another Region), then restore. ([EBS snapshots](/docs/storage/ebs-snapshots)) - **"Cheapest way to keep snapshots for years, rarely needed"** → EBS Snapshots Archive. ([EBS snapshots](/docs/storage/ebs-snapshots)) - **"Protect against accidental deletion of snapshots"** → Recycle Bin retention rule. ([EBS snapshots](/docs/storage/ebs-snapshots)) - **"Restored volume must deliver full performance immediately"** → Fast Snapshot Restore. ([EBS snapshots](/docs/storage/ebs-snapshots)) - **"Boot volume"** → gp2, gp3, io1 or io2; never st1 or sc1. ([EBS volume types](/docs/storage/ebs-volume-types)) - **"Increase IOPS without increasing size"** → gp3 (or io1/io2), not gp2. ([EBS volume types](/docs/storage/ebs-volume-types)) - **"More than 64,000 IOPS", "mission-critical database", "sub-millisecond"** → io2 Block Express. ([EBS volume types](/docs/storage/ebs-volume-types)) - **"Big data, log processing, data warehouse, throughput"** → st1. ([EBS volume types](/docs/storage/ebs-volume-types)) - **"Infrequently accessed, lowest cost HDD"** → sc1. ([EBS volume types](/docs/storage/ebs-volume-types)) - **"gp2 volume needs more IOPS"** → change it to gp3 with Elastic Volumes, no downtime. ([EBS volume types](/docs/storage/ebs-volume-types)) - **"Attach the same EBS volume to multiple instances"** → Multi-Attach, **io1/io2 only**, **same AZ**, **up to 16** instances. ([EBS Multi-Attach](/docs/storage/ebs-multi-attach)) - **"Clustered application needs shared block storage for high availability"** → io2 with Multi-Attach. ([EBS Multi-Attach](/docs/storage/ebs-multi-attach)) - **"Many web servers share files across AZs"** → EFS, not Multi-Attach. ([EBS Multi-Attach](/docs/storage/ebs-multi-attach)) - **"Encrypt an existing unencrypted EBS volume"** → snapshot, copy (or restore) with encryption, create a new volume, swap it in. ([EBS encryption](/docs/storage/ebs-encryption)) - **"Make sure all new EBS volumes are encrypted"** → turn on EBS encryption by default in each Region (and enforce it with an SCP or AWS Config rule). ([EBS encryption](/docs/storage/ebs-encryption)) - **"Highest possible IOPS", "very low latency local storage"** → instance store (storage optimized types). ([Instance store](/docs/storage/instance-store)) - **"Temporary data, cache, buffer, scratch space"** → instance store. ([Instance store](/docs/storage/instance-store)) - **"Data must survive stop/start"** → EBS, not instance store. ([Instance store](/docs/storage/instance-store)) - **"Shared file system for many Linux instances across AZs"**, **"WordPress / CMS shared content"** → EFS. ([Amazon EFS](/docs/storage/efs)) - **"POSIX-compliant shared storage"**, **"NFS"** → EFS. ([Amazon EFS](/docs/storage/efs)) - **"Windows file share"** → not EFS: FSx for Windows File Server. ([Amazon EFS](/docs/storage/efs)) - **"Unpredictable or spiky throughput"** → Elastic throughput. **"Known, steady high throughput regardless of size"** → Provisioned. ([Amazon EFS](/docs/storage/efs)) - **"Reduce cost of rarely used files"** → lifecycle policy to IA / Archive. ([Amazon EFS](/docs/storage/efs)) - **"Cheapest, dev/test, single AZ is fine"** → One Zone (with One Zone-IA). ([Amazon EFS](/docs/storage/efs)) - **"Instances can't mount EFS"** → check the mount target's security group allows NFS (2049). ([Amazon EFS](/docs/storage/efs)) - **"Windows file share", "SMB", "NTFS", "Active Directory", "DFS"** → FSx for Windows File Server. **"Highly available"** → Multi-AZ deployment. ([Amazon FSx](/docs/storage/fsx)) - **"HPC", "machine learning", "parallel file system", "process S3 data at high speed"** → FSx for Lustre. ([Amazon FSx](/docs/storage/fsx)) - **"Temporary, short-term, cost-optimised HPC storage"** → Lustre **scratch**. **"Long-term, replicated"** → Lustre **persistent**. ([Amazon FSx](/docs/storage/fsx)) - **"NFS, SMB and iSCSI from one system", "move NetApp / NAS to AWS"** → FSx for NetApp ONTAP. ([Amazon FSx](/docs/storage/fsx)) - **"Move ZFS file servers", "instant clones over NFS"** → FSx for OpenZFS. ([Amazon FSx](/docs/storage/fsx)) - **"Lowest cost per GB for one server's disk"** → EBS (gp3, or st1/sc1 for throughput data), not EFS. ([EBS vs EFS vs instance store](/docs/storage/ebs-vs-efs-vs-instance-store)) - **"Millions of IOPS on one instance"** → instance store. ([EBS vs EFS vs instance store](/docs/storage/ebs-vs-efs-vs-instance-store)) - **"Object", "static website", "data lake", "unlimited storage"** → S3. **"Archive, retrieve in hours"** → S3 Glacier. ([Storage comparison](/docs/storage/storage-comparison)) - **"Block storage for EC2"** → EBS; **"temporary, highest IOPS"** → instance store. ([Storage comparison](/docs/storage/storage-comparison)) - **"Shared POSIX file system"** → EFS; **"SMB / Windows"** → FSx for Windows; **"HPC / Lustre"** → FSx for Lustre. ([Storage comparison](/docs/storage/storage-comparison)) - **"On-premises apps need access to cloud storage"** → Storage Gateway. **"SFTP into S3"** → Transfer Family. **"Copy large data sets online"** → DataSync. **"Petabytes, slow or no network"** → Snowball Edge in exam answers (closed to new customers now). ([Storage comparison](/docs/storage/storage-comparison)) ## Load Balancing & Auto Scaling [#load-balancing--auto-scaling] - **"Handle more load by adding instances"**, **"elastic"** → horizontal scaling with an Auto Scaling group. ([Load Balancing & Auto Scaling](/docs/scaling)) - **"Survive the failure of an AZ / data centre"** → instances in at least two AZs behind a load balancer. ([Load Balancing & Auto Scaling](/docs/scaling)) - **"Database needs more power"** → usually vertical scaling (a bigger instance class), or read replicas. ([Load Balancing & Auto Scaling](/docs/scaling)) - **"Highly available and scalable web tier"** → ALB + Auto Scaling group across multiple AZs. ([Load Balancing & Auto Scaling](/docs/scaling)) - **"Single DNS name in front of many instances"**, **"distribute traffic"**, **"remove unhealthy instances"** → Elastic Load Balancing. ([Elastic Load Balancing](/docs/scaling/elb-overview)) - **"Instances must only accept traffic from the load balancer"** → instance security group references the load balancer's security group. ([Elastic Load Balancing](/docs/scaling/elb-overview)) - **"HTTP routing by path or host"** → ALB. **"TCP/UDP, extreme performance, static IP"** → NLB. **"Third-party firewall appliances"** → GWLB. ([Elastic Load Balancing](/docs/scaling/elb-overview)) - **"Route by URL path / hostname / query string / header"** → ALB listener rules. ([Application Load Balancer](/docs/scaling/alb)) - **"Microservices or containers behind one load balancer"**, **"ECS dynamic ports"** → ALB. ([Application Load Balancer](/docs/scaling/alb)) - **"Invoke a Lambda function over HTTP from a load balancer"** → ALB with a Lambda target group. ([Application Load Balancer](/docs/scaling/alb)) - **"Redirect HTTP to HTTPS"** → ALB redirect action. ([Application Load Balancer](/docs/scaling/alb)) - **"The application needs the client's IP address"** → read `X-Forwarded-For`. ([Application Load Balancer](/docs/scaling/alb)) - **"Static IP for an ALB"** → put an NLB in front with the ALB as its target, or use Global Accelerator. ([Application Load Balancer](/docs/scaling/alb)) - **"TCP / UDP traffic"**, **"millions of requests per second"**, **"ultra-low latency"** → NLB. ([Network Load Balancer](/docs/scaling/nlb)) - **"Static IP address" or "Elastic IP" for a load balancer**, **"clients allow-list our IPs"** → NLB. ([Network Load Balancer](/docs/scaling/nlb)) - **"Static IPs and path-based routing"** → NLB with an ALB as the target (or Global Accelerator in front of an ALB). ([Network Load Balancer](/docs/scaling/nlb)) - **"End-to-end encryption, targets must decrypt"** → NLB with a TCP listener on 443 (passthrough). ([Network Load Balancer](/docs/scaling/nlb)) - **"Gaming, VoIP, IoT over UDP"** → NLB. ([Network Load Balancer](/docs/scaling/nlb)) - **"Third-party firewall / IDS / IPS / deep packet inspection appliances"**, **"inspect all traffic"** → Gateway Load Balancer. ([Gateway Load Balancer](/docs/scaling/gwlb)) - **"GENEVE protocol on port 6081"** → GWLB. ([Gateway Load Balancer](/docs/scaling/gwlb)) - **"Layer 3"** load balancer → GWLB (ALB is layer 7, NLB layer 4). ([Gateway Load Balancer](/docs/scaling/gwlb)) - **"Users must keep their session on the same instance"** → sticky sessions (ALB cookie, or source IP on an NLB). ([Sticky sessions and cross-zone load balancing](/docs/scaling/sticky-sessions-cross-zone)) - **"Load is uneven since enabling stickiness"** → that's the expected side effect; store sessions in ElastiCache or DynamoDB instead. ([Sticky sessions and cross-zone load balancing](/docs/scaling/sticky-sessions-cross-zone)) - **"Uneven instance counts across AZs cause overloaded instances"** → turn on cross-zone load balancing. ([Sticky sessions and cross-zone load balancing](/docs/scaling/sticky-sessions-cross-zone)) - **"HTTPS for the website, free certificate that renews itself"** → ACM certificate on the load balancer's HTTPS listener. ([SSL/TLS, SNI and deregistration delay](/docs/scaling/ssl-tls-sni)) - **"Host several HTTPS domains on one load balancer"** → ALB or NLB with multiple certificates and **SNI**. ([SSL/TLS, SNI and deregistration delay](/docs/scaling/ssl-tls-sni)) - **"Classic Load Balancer with several domains"** → needs one CLB per certificate (or migrate to ALB). ([SSL/TLS, SNI and deregistration delay](/docs/scaling/ssl-tls-sni)) - **"Support old clients' TLS versions"** → choose a security policy that allows them. ([SSL/TLS, SNI and deregistration delay](/docs/scaling/ssl-tls-sni)) - **"In-flight requests fail during scale-in or deployments"** → increase the deregistration delay. **"Deployments take 5 minutes per instance for short requests"** → lower it. ([SSL/TLS, SNI and deregistration delay](/docs/scaling/ssl-tls-sni)) - **"Automatically replace failed instances"**, **"maintain a fixed number of instances"** → Auto Scaling group (even with min = max). ([Auto Scaling groups](/docs/scaling/auto-scaling-groups)) - **"Replace instances the load balancer marks unhealthy"** → turn on ELB health checks for the group. ([Auto Scaling groups](/docs/scaling/auto-scaling-groups)) - **"Highly available across AZs"** → the group's subnets span at least two AZs. ([Auto Scaling groups](/docs/scaling/auto-scaling-groups)) - **"Change the AMI or instance type for new instances"** → a new launch template version (then an [instance refresh](/docs/scaling/scaling-policies#instance-refresh) to replace existing ones). ([Auto Scaling groups](/docs/scaling/auto-scaling-groups)) - **"Cheapest for fault-tolerant work, keep a baseline"** → mixed instances policy with On-Demand base capacity plus Spot. ([Auto Scaling groups](/docs/scaling/auto-scaling-groups)) - **"Keep average CPU at 50%"**, **"simplest way to scale on a metric"** → target tracking. ([Scaling policies](/docs/scaling/scaling-policies)) - **"Scale every Friday at 5 pm"**, **"known event"** → scheduled scaling. ([Scaling policies](/docs/scaling/scaling-policies)) - **"Daily or weekly cyclical traffic, scale ahead of demand"** → predictive scaling. ([Scaling policies](/docs/scaling/scaling-policies)) - **"Scale by number of requests per instance"** → target tracking on `ALBRequestCountPerTarget`. ([Scaling policies](/docs/scaling/scaling-policies)) - **"Instances take a long time to boot, so scale-out is too slow"** → warm pool (and a golden AMI). ([Scaling policies](/docs/scaling/scaling-policies)) - **"Roll out a new AMI to all instances in the group with no downtime"** → new launch template version + instance refresh. ([Scaling policies](/docs/scaling/scaling-policies)) - **"Run a script before an instance is terminated"** → lifecycle hook. ([Scaling policies](/docs/scaling/scaling-policies)) - **"Group scales out again too soon"** → cooldown (simple scaling) or instance warmup. ([Scaling policies](/docs/scaling/scaling-policies)) - **"Set up scaling for EC2, ECS, DynamoDB and Aurora of one application from a single place"**, **"scaling plan"** → AWS Auto Scaling. ([Scaling policies](/docs/scaling/scaling-policies)) - **"Scale DynamoDB capacity, ECS tasks or Aurora replicas automatically"** → Application Auto Scaling (through each service's auto scaling settings). ([Scaling policies](/docs/scaling/scaling-policies)) ## Databases [#databases] - **"Relational", "SQL", "joins", "transactions", "OLTP"** → RDS or Aurora. ([Databases](/docs/databases)) - **"MySQL or PostgreSQL with the best performance and availability", "less management"** → Aurora. ([Databases](/docs/databases)) - **"Oracle or SQL Server with access to the operating system"** → RDS Custom. ([Databases](/docs/databases)) - **"Serverless NoSQL", "key-value", "millions of requests per second", "schema changes often"** → DynamoDB. ([Databases](/docs/databases)) - **"Cache", "sub-millisecond", "session store", "reduce database load"** → ElastiCache (or DAX for DynamoDB). ([Databases](/docs/databases)) - **"MongoDB"** → DocumentDB. **"Graph", "relationships", "social network", "fraud rings"** → Neptune. **"Cassandra", "CQL"** → Keyspaces. **"Time series", "IoT sensor data"** → Timestream. ([Databases](/docs/databases)) - **"Analytics", "data warehouse", "OLAP", "BI"** → Redshift. ([Databases](/docs/databases)) - **"Managed relational database", "MySQL / PostgreSQL / Oracle / SQL Server", "less operational overhead"** → RDS. ([Amazon RDS](/docs/databases/rds)) - **"Database storage grows unpredictably", "avoid running out of space"** → turn on storage auto scaling with a maximum threshold. ([Amazon RDS](/docs/databases/rds)) - **"Need OS access or custom patches on Oracle or SQL Server"** → RDS Custom. **"Full control of any engine"** → database on EC2. ([Amazon RDS](/docs/databases/rds)) - **"Stop a database for months to save money"** → snapshot, delete, restore later (a stopped instance restarts after 7 days). ([Amazon RDS](/docs/databases/rds)) - **"Read-heavy", "reporting queries slow down production", "scale reads"** → read replicas. ([Read replicas and Multi-AZ](/docs/databases/rds-read-replicas-multi-az)) - **"High availability", "survive an AZ failure", "automatic failover", "no data loss"** → Multi-AZ. ([Read replicas and Multi-AZ](/docs/databases/rds-read-replicas-multi-az)) - **"Replica lag", "reads may be stale"** → asynchronous read replicas. ([Read replicas and Multi-AZ](/docs/databases/rds-read-replicas-multi-az)) - **"Disaster recovery to another Region"** → cross-Region read replica (promote it). ([Read replicas and Multi-AZ](/docs/databases/rds-read-replicas-multi-az)) - **"Reduce cross-AZ replication cost"** → RDS replicas in the same Region are free to replicate to. ([Read replicas and Multi-AZ](/docs/databases/rds-read-replicas-multi-az)) - **"Make an existing database Multi-AZ with no downtime"** → modify it. ([Read replicas and Multi-AZ](/docs/databases/rds-read-replicas-multi-az)) - **"MySQL or PostgreSQL compatible, high performance, high availability, minimal management"** → Aurora. ([Amazon Aurora](/docs/databases/aurora)) - **"Six copies across three AZs", "self-healing storage"** → Aurora. ([Amazon Aurora](/docs/databases/aurora)) - **"Send read traffic to replicas automatically"** → reader endpoint. **"Analytics on specific bigger replicas"** → custom endpoint. ([Amazon Aurora](/docs/databases/aurora)) - **"Replicas scale with read load"** → Aurora Replica auto scaling. ([Amazon Aurora](/docs/databases/aurora)) - **"Undo a mistake quickly without restoring a backup"** → Backtrack (Aurora MySQL). ([Amazon Aurora](/docs/databases/aurora)) - **"Unpredictable or intermittent workload", "no capacity planning", "pay per second"** → Aurora Serverless. ([Aurora advanced](/docs/databases/aurora-advanced)) - **"Global application, low-latency reads in several Regions, Region-level DR with RPO of about a second and RTO under a minute"** → Aurora Global Database. ([Aurora advanced](/docs/databases/aurora-advanced)) - **"ML predictions from SQL", "SageMaker or Comprehend from the database"** → Aurora machine learning. ([Aurora advanced](/docs/databases/aurora-advanced)) - **"Run SQL Server applications on Aurora with few code changes"** → Babelfish for Aurora PostgreSQL. ([Aurora advanced](/docs/databases/aurora-advanced)) - **"Restore to a specific time a few minutes ago"** → automated backups with point-in-time recovery (up to 35 days). ([Backups, restore and cloning](/docs/databases/backups-restore-cloning)) - **"Keep a backup for years", "after the database is deleted"** → manual snapshot. ([Backups, restore and cloning](/docs/databases/backups-restore-cloning)) - **"Move an on-premises MySQL database to Aurora"** → Percona XtraBackup files in S3, restore into Aurora (or AWS DMS). ([Backups, restore and cloning](/docs/databases/backups-restore-cloning)) - **"Create a test or staging copy of production quickly and cheaply"** → Aurora cloning. ([Backups, restore and cloning](/docs/databases/backups-restore-cloning)) - **"Pause an RDS database for months"** → snapshot, delete, restore later. ([Backups, restore and cloning](/docs/databases/backups-restore-cloning)) - **"Encrypt an existing unencrypted RDS database"** → snapshot, copy with encryption, restore. ([Security and RDS Proxy](/docs/databases/rds-security-proxy)) - **"Connect to RDS without a password, using IAM roles"** → IAM database authentication (MySQL, MariaDB, PostgreSQL). ([Security and RDS Proxy](/docs/databases/rds-security-proxy)) - **"Rotate database credentials automatically"** → Secrets Manager. ([Security and RDS Proxy](/docs/databases/rds-security-proxy)) - **"Lambda functions exhaust database connections", "too many connections"** → RDS Proxy. ([Security and RDS Proxy](/docs/databases/rds-security-proxy)) - **"Reduce failover time for applications"** → RDS Proxy. ([Security and RDS Proxy](/docs/databases/rds-security-proxy)) - **"Enforce IAM authentication to the database"** → RDS Proxy (or IAM database authentication). ([Security and RDS Proxy](/docs/databases/rds-security-proxy)) - **"Reduce read load on RDS", "frequently read data", "sub-millisecond reads"** → ElastiCache. ([Amazon ElastiCache](/docs/databases/elasticache)) - **"Store user sessions so the app is stateless"** → ElastiCache (or DynamoDB). ([Amazon ElastiCache](/docs/databases/elasticache)) - **"Cache must survive node failure", "Multi-AZ", "backups", "sorted sets"** → Valkey / Redis OSS. ([Amazon ElastiCache](/docs/databases/elasticache)) - **"Simple cache, multithreaded, data loss is fine"** → Memcached. ([Amazon ElastiCache](/docs/databases/elasticache)) - **"Data in the cache is stale"** → write-through or a TTL. **"Cache holds data nobody reads"** → lazy loading. ([Amazon ElastiCache](/docs/databases/elasticache)) - **"Leaderboard"** → Redis/Valkey sorted sets. ([Amazon ElastiCache](/docs/databases/elasticache)) - **"Least application change for caching DynamoDB"** → DAX, not ElastiCache (see [DynamoDB advanced](/docs/databases/dynamodb-advanced#dynamodb-accelerator-dax)). ([Amazon ElastiCache](/docs/databases/elasticache)) - **"Serverless NoSQL", "key-value", "single-digit millisecond", "any scale"** → DynamoDB. ([Amazon DynamoDB](/docs/databases/dynamodb)) - **"Schema changes often", "flexible attributes"** → DynamoDB. ([Amazon DynamoDB](/docs/databases/dynamodb)) - **"Unpredictable traffic", "sudden spikes", "no capacity planning"** → on-demand mode. ([Amazon DynamoDB](/docs/databases/dynamodb)) - **"Steady, predictable traffic, lowest cost"** → provisioned mode with auto scaling. ([Amazon DynamoDB](/docs/databases/dynamodb)) - **"Store session data", "shopping cart"** → DynamoDB (with TTL), as an alternative to ElastiCache. ([Amazon DynamoDB](/docs/databases/dynamodb)) - **"Mostly stored, rarely read table, reduce cost"** → Standard-IA table class. ([Amazon DynamoDB](/docs/databases/dynamodb)) - **"Items larger than 400 KB"** → store the object in S3 and its key in DynamoDB. ([Amazon DynamoDB](/docs/databases/dynamodb)) - **"Microsecond reads for DynamoDB", "hot items", "no code changes"** → DAX. ([DynamoDB advanced](/docs/databases/dynamodb-advanced)) - **"Cache aggregation results computed by the app"** → ElastiCache. ([DynamoDB advanced](/docs/databases/dynamodb-advanced)) - **"React to item changes", "trigger Lambda on insert"** → DynamoDB Streams. ([DynamoDB advanced](/docs/databases/dynamodb-advanced)) - **"Keep change records longer than 24 hours", "many consumers"** → Kinesis Data Streams for DynamoDB. ([DynamoDB advanced](/docs/databases/dynamodb-advanced)) - **"Multi-Region, active-active, low latency reads and writes everywhere"** → global tables. ([DynamoDB advanced](/docs/databases/dynamodb-advanced)) - **"Delete old items automatically", "expire sessions"** → TTL. ([DynamoDB advanced](/docs/databases/dynamodb-advanced)) - **"Restore to a point in time in the last 35 days"** → PITR. **"Keep backups for years"** → on-demand backups (AWS Backup for cross-Region copies). ([DynamoDB advanced](/docs/databases/dynamodb-advanced)) - **"Analyse DynamoDB data with SQL without using capacity"** → export to S3, query with Athena. ([DynamoDB advanced](/docs/databases/dynamodb-advanced)) - **"Load a large CSV into a new DynamoDB table cheaply"** → import from S3. ([DynamoDB advanced](/docs/databases/dynamodb-advanced)) - **"MongoDB", "JSON documents", "MongoDB compatible"** → DocumentDB. ([DocumentDB, Neptune and Keyspaces](/docs/databases/documentdb-neptune-keyspaces)) - **"Graph", "relationships", "social network", "knowledge graph", "fraud rings", "recommendations"** → Neptune. ([DocumentDB, Neptune and Keyspaces](/docs/databases/documentdb-neptune-keyspaces)) - **"Change events from a graph database"** → Neptune Streams. ([DocumentDB, Neptune and Keyspaces](/docs/databases/documentdb-neptune-keyspaces)) - **"Apache Cassandra", "CQL"** → Keyspaces. ([DocumentDB, Neptune and Keyspaces](/docs/databases/documentdb-neptune-keyspaces)) - **"Serverless NoSQL with no particular open-source API"** → DynamoDB. ([DocumentDB, Neptune and Keyspaces](/docs/databases/documentdb-neptune-keyspaces)) - **"Time series data", "IoT sensor readings over time", "metrics with timestamps"** → Timestream (Timestream for InfluxDB for new designs). ([Amazon Timestream](/docs/databases/timestream)) - **"Recent data fast, old data cheap, automatically"** → Timestream's storage tiering. ([Amazon Timestream](/docs/databases/timestream)) ## Amazon S3 [#amazon-s3] - **"Store any amount of files cheaply, accessed over HTTP"**, **"durable object storage"** → S3. ([Amazon S3](/docs/s3)) - **"Object larger than 5 GB"** → multipart upload (required). **Largest object** → 50 TB. ([Amazon S3](/docs/s3)) - **"Bucket names must be unique"** → globally, unless you use the account regional namespace. ([Amazon S3](/docs/s3)) - **"Give an EC2 instance access to S3"** → IAM role (instance profile), not access keys. ([Security and bucket policies](/docs/s3/security-bucket-policies)) - **"Grant access to another AWS account"** → bucket policy (cross-account). ([Security and bucket policies](/docs/s3/security-bucket-policies)) - **"Make objects publicly readable"** → bucket policy with `Principal: "*"` and Block Public Access off. ([Security and bucket policies](/docs/s3/security-bucket-policies)) - **"Prevent any bucket in the account from ever being public"** → Block Public Access at the account (or organization) level. ([Security and bucket policies](/docs/s3/security-bucket-policies)) - **"Explicit deny in a bucket policy vs allow in IAM"** → deny wins. ([Security and bucket policies](/docs/s3/security-bucket-policies)) - **"Host a static website cheaply with no servers"** → S3 static website hosting. ([Static website hosting](/docs/s3/static-website)) - **"403 Forbidden on the S3 website"** → add a bucket policy allowing public `s3:GetObject` (and turn off Block Public Access). ([Static website hosting](/docs/s3/static-website)) - **"Static website with HTTPS"** → CloudFront in front of S3. ([Static website hosting](/docs/s3/static-website)) - **"Website with server-side code"** → not S3 alone; use compute. ([Static website hosting](/docs/s3/static-website)) - **"Protect against accidental deletion or overwrite"** → versioning (plus MFA Delete for more protection). ([Versioning and replication](/docs/s3/versioning-replication)) - **"Restore a deleted object"** → delete the delete marker (or copy the previous version). ([Versioning and replication](/docs/s3/versioning-replication)) - **"Copy objects to another Region automatically", "disaster recovery for S3"** → CRR. ([Versioning and replication](/docs/s3/versioning-replication)) - **"Aggregate logs from many buckets in the same Region"** → SRR. ([Versioning and replication](/docs/s3/versioning-replication)) - **"Replicate objects that existed before replication was turned on"** → S3 Batch Replication. ([Versioning and replication](/docs/s3/versioning-replication)) - **"Replication within a guaranteed time"** → S3 Replication Time Control. ([Versioning and replication](/docs/s3/versioning-replication)) - **"Frequently accessed"** → Standard. **"Unknown or changing access patterns"** → Intelligent-Tiering. ([Storage classes](/docs/s3/storage-classes)) - **"Infrequent but needs immediate access", "backups, DR"** → Standard-IA. ([Storage classes](/docs/s3/storage-classes)) - **"Can be re-created", "secondary copy", "cheapest immediate access"** → One Zone-IA. ([Storage classes](/docs/s3/storage-classes)) - **"Archive, read once a quarter, milliseconds"** → Glacier Instant Retrieval. ([Storage classes](/docs/s3/storage-classes)) - **"Archive, retrieval in minutes or hours"** → Glacier Flexible Retrieval (Expedited 1–5 min, Bulk free). ([Storage classes](/docs/s3/storage-classes)) - **"Cheapest storage, retrieval within 12 or 48 hours", "keep for years for compliance"** → Glacier Deep Archive. ([Storage classes](/docs/s3/storage-classes)) - **"Single-digit millisecond, very high request rate, same AZ as compute"** → S3 Express One Zone. ([Storage classes](/docs/s3/storage-classes)) - **"Automatically move objects to a cheaper class after N days"** → lifecycle transition action. ([Lifecycle rules](/docs/s3/lifecycle-rules)) - **"Delete old log files automatically"** → lifecycle expiration action. ([Lifecycle rules](/docs/s3/lifecycle-rules)) - **"Old versions are costing money"** → expire noncurrent versions. ([Lifecycle rules](/docs/s3/lifecycle-rules)) - **"Hidden storage cost from failed uploads"** → abort incomplete multipart uploads. ([Lifecycle rules](/docs/s3/lifecycle-rules)) - **"Which objects should move to Standard-IA, and when?"** → Storage Class Analysis. ([Lifecycle rules](/docs/s3/lifecycle-rules)) - **"Recover deleted objects within 48 hours for a year"** → versioning + transition noncurrent versions to Deep Archive. ([Lifecycle rules](/docs/s3/lifecycle-rules)) - **"Share a large dataset with other accounts; they should pay for downloads"** → Requester Pays. ([Requester Pays](/docs/s3/requester-pays)) - **"Requester Pays and anonymous users"** → not allowed; requesters must be authenticated. ([Requester Pays](/docs/s3/requester-pays)) - **"Run code when an object is uploaded", "thumbnail on upload"** → S3 event notification to Lambda. ([Event notifications](/docs/s3/event-notifications)) - **"Queue uploaded files for processing"** → event notification to SQS. ([Event notifications](/docs/s3/event-notifications)) - **"Notify several subscribers of a new object"** → SNS (fan-out). ([Event notifications](/docs/s3/event-notifications)) - **"Advanced filtering, many targets, archive and replay of S3 events"** → EventBridge. ([Event notifications](/docs/s3/event-notifications)) - **"S3 can't send to the queue"** → the queue's access policy must allow `s3.amazonaws.com`. ([Event notifications](/docs/s3/event-notifications)) - **"Upload files larger than 5 GB"** → multipart upload (required). **"Faster upload of large files"** → multipart upload. ([Performance](/docs/s3/performance)) - **"Faster uploads from far away", "users around the world upload to one bucket"** → S3 Transfer Acceleration. ([Performance](/docs/s3/performance)) - **"Download faster", "read only the beginning of a file"** → byte-range fetches. ([Performance](/docs/s3/performance)) - **"Higher request rate"** → spread objects across more prefixes. ([Performance](/docs/s3/performance)) - **"HTTP 503 Slow Down"** → too many requests on one prefix; spread out and retry with backoff. ([Performance](/docs/s3/performance)) - **"Encrypt all existing unencrypted objects", "change tags on millions of objects"** → S3 Batch Operations (with S3 Inventory as the list). ([Batch Operations and Storage Lens](/docs/s3/batch-operations-storage-lens)) - **"Restore many objects from Glacier at once"** → Batch Operations. ([Batch Operations and Storage Lens](/docs/s3/batch-operations-storage-lens)) - **"Replicate existing objects"** → S3 Batch Replication. ([Batch Operations and Storage Lens](/docs/s3/batch-operations-storage-lens)) - **"Organization-wide view of S3 usage, cost savings and data protection"** → S3 Storage Lens. ([Batch Operations and Storage Lens](/docs/s3/batch-operations-storage-lens)) - **"Keep Storage Lens metrics 15 months", "publish to CloudWatch"** → advanced metrics. ([Batch Operations and Storage Lens](/docs/s3/batch-operations-storage-lens)) - **"Encryption with no management at all"** → SSE-S3 (already on by default). ([Encryption](/docs/s3/encryption)) - **"Control the key", "audit key usage", "rotate keys"** → SSE-KMS. ([Encryption](/docs/s3/encryption)) - **"KMS throttling errors on a busy bucket"** → S3 Bucket Keys, or ask for a higher KMS quota. ([Encryption](/docs/s3/encryption)) - **"Two layers of encryption for compliance"** → DSSE-KMS. ([Encryption](/docs/s3/encryption)) - **"Keys must stay outside AWS, S3 does the encryption"** → SSE-C (HTTPS only). ([Encryption](/docs/s3/encryption)) - **"Data must be encrypted before it leaves our servers"** → client-side encryption. ([Encryption](/docs/s3/encryption)) - **"Refuse uploads over HTTP"** → bucket policy denying when `aws:SecureTransport` is false. ([Encryption](/docs/s3/encryption)) - **"Only allow objects encrypted with SSE-KMS"** → bucket policy denying `PutObject` without the `aws:kms` header. ([Encryption](/docs/s3/encryption)) - **"Website on one bucket can't load files from another bucket", "browser blocks the request", "CORS error"** → add a CORS configuration to the bucket being requested, allowing the website's origin. ([CORS](/docs/s3/cors)) - **"Allow any website to load these public files"** → CORS with `AllowedOrigins: ["*"]`. ([CORS](/docs/s3/cors)) - **"Require MFA to permanently delete object versions"** → MFA Delete (versioning required, root user, CLI). ([MFA Delete and access logs](/docs/s3/mfa-delete-access-logs)) - **"Who can enable MFA Delete?"** → only the bucket owner's root user. ([MFA Delete and access logs](/docs/s3/mfa-delete-access-logs)) - **"Audit all requests to a bucket, including denied ones"** → S3 server access logging to another bucket. ([MFA Delete and access logs](/docs/s3/mfa-delete-access-logs)) - **"Log bucket grows uncontrollably"** → it's logging into itself. ([MFA Delete and access logs](/docs/s3/mfa-delete-access-logs)) - **"Give temporary access to a private object without making it public"**, **"users without AWS credentials download one file"** → presigned URL. ([Presigned URLs](/docs/s3/presigned-urls)) - **"Let users upload directly to S3 from the browser"** → presigned `PUT` URL. ([Presigned URLs](/docs/s3/presigned-urls)) - **"URL stopped working before its expiry time"** → it was signed with temporary credentials that expired, or the signer lost permission. ([Presigned URLs](/docs/s3/presigned-urls)) - **"WORM", "regulatory retention", "no one can delete, not even root"** → S3 Object Lock in compliance mode. ([Object Lock and Vault Lock](/docs/s3/object-lock-vault-lock)) - **"Prevent deletion but let a few admins override"** → governance mode. ([Object Lock and Vault Lock](/docs/s3/object-lock-vault-lock)) - **"Keep an object indefinitely for a lawsuit, no fixed date"** → legal hold. ([Object Lock and Vault Lock](/docs/s3/object-lock-vault-lock)) - **"WORM for a Glacier vault"** → Glacier Vault Lock. ([Object Lock and Vault Lock](/docs/s3/object-lock-vault-lock)) - **"Object Lock prerequisite"** → versioning enabled. ([Object Lock and Vault Lock](/docs/s3/object-lock-vault-lock)) - **"Many teams share a bucket, the bucket policy is too complex"** → S3 Access Points with per-team policies. ([Access Points and Object Lambda](/docs/s3/access-points-object-lambda)) - **"Access the bucket only from inside a VPC"** → an access point with VPC network origin, plus a VPC endpoint. ([Access Points and Object Lambda](/docs/s3/access-points-object-lambda)) - **"Change data as it's read, without storing copies"** (redact, convert, resize) → S3 Object Lambda. ([Access Points and Object Lambda](/docs/s3/access-points-object-lambda)) ## DNS & Content Delivery [#dns--content-delivery] - **"Domain name", "DNS", "route users to the nearest Region", "DNS failover"** → Route 53. ([DNS & Content Delivery](/docs/edge)) - **"Cache static content globally", "reduce latency for images and video", "offload the origin"** → CloudFront. ([DNS & Content Delivery](/docs/edge)) - **"Static IP addresses for a global application", "TCP or UDP", "gaming", "fast regional failover without DNS caching"** → Global Accelerator. ([DNS & Content Delivery](/docs/edge)) - **"Run code at the edge to change requests or responses"** → CloudFront Functions or Lambda@Edge. ([DNS & Content Delivery](/docs/edge)) - **"Authoritative DNS where you manage the records"** → Route 53 hosted zone. ([DNS basics](/docs/edge/dns-basics)) - **"Changes to DNS take time to reach users"** → resolvers cache answers for the TTL. ([DNS basics](/docs/edge/dns-basics)) - **"Which AWS service has a 100% availability SLA?"** → Route 53. ([DNS basics](/docs/edge/dns-basics)) - **"Map a name to IPv4"** → A. **"IPv6"** → AAAA. **"Name to another name"** → CNAME. **"Who answers for this domain"** → NS. ([Records and hosted zones](/docs/edge/route53-records-zones)) - **"Internal DNS names for resources in a VPC"** → private hosted zone (with DNS hostnames and resolution on). ([Records and hosted zones](/docs/edge/route53-records-zones)) - **"Clients still go to the old IP address after a change"** → the TTL is too high; lower it before changes. ([Records and hosted zones](/docs/edge/route53-records-zones)) - **"Reduce Route 53 query costs"** → raise the TTL (or use alias records to AWS resources, which are free). ([Records and hosted zones](/docs/edge/route53-records-zones)) - **"Point the root domain (zone apex) to a load balancer or CloudFront"** → alias record. ([CNAME vs alias](/docs/edge/route53-alias)) - **"Point a name to a non-AWS hostname"** → CNAME (not at the apex). ([CNAME vs alias](/docs/edge/route53-alias)) - **"Avoid DNS query charges for AWS resources"**, **"follow the load balancer's changing IPs"** → alias. ([CNAME vs alias](/docs/edge/route53-alias)) - **"Alias to an EC2 instance"** → not possible; use an A record with an Elastic IP. ([CNAME vs alias](/docs/edge/route53-alias)) - **"Send 10% of users to the new version"**, **"gradual migration"** → weighted. ([Routing policies](/docs/edge/route53-routing-policies)) - **"Best performance for users worldwide", "lowest latency"** → latency-based. ([Routing policies](/docs/edge/route53-routing-policies)) - **"Active-passive", "disaster recovery site when the primary fails"** → failover (with a health check). ([Routing policies](/docs/edge/route53-routing-policies)) - **"Users in a country must see a localized site", "restrict by country", "legal requirements"** → geolocation. ([Routing policies](/docs/edge/route53-routing-policies)) - **"Shift more traffic to one Region based on distance"**, **"bias"** → geoproximity. ([Routing policies](/docs/edge/route53-routing-policies)) - **"Route users of a specific ISP or IP range"** → IP-based. ([Routing policies](/docs/edge/route53-routing-policies)) - **"Return several healthy IP addresses"** → multivalue answer. ([Routing policies](/docs/edge/route53-routing-policies)) - **"Health checks with one record holding several IPs"** → not possible with simple; use multivalue. ([Routing policies](/docs/edge/route53-routing-policies)) - **"Automatic DNS failover to a healthy Region"** → health checks linked to records (failover, latency, weighted…). ([Health checks](/docs/edge/route53-health-checks)) - **"Health check for a resource in a private subnet"** → health check on a CloudWatch alarm (or a private endpoint health check). ([Health checks](/docs/edge/route53-health-checks)) - **"Keep the site healthy while one server is in maintenance"** → calculated health check. ([Health checks](/docs/edge/route53-health-checks)) - **"Health checks keep failing although the app works"** → allow the Route 53 health checker IP ranges through the firewall. ([Health checks](/docs/edge/route53-health-checks)) - **"Check that the page contains specific text"** → string matching (first 5,120 bytes). ([Health checks](/docs/edge/route53-health-checks)) - **"Domain bought from another registrar, use Route 53"** → create a public hosted zone and update the NS records at the registrar. ([Registrar and hybrid DNS](/docs/edge/route53-registrar-hybrid-dns)) - **"On-premises servers must resolve private hosted zone names"** → Resolver **inbound** endpoint. ([Registrar and hybrid DNS](/docs/edge/route53-registrar-hybrid-dns)) - **"EC2 instances must resolve on-premises domain names"** → Resolver **outbound** endpoint + forwarding rule. ([Registrar and hybrid DNS](/docs/edge/route53-registrar-hybrid-dns)) - **"Block instances from resolving malicious domains", "DNS exfiltration"** → Route 53 Resolver DNS Firewall. ([Registrar and hybrid DNS](/docs/edge/route53-registrar-hybrid-dns)) - **"Cache static content globally", "reduce load on the origin", "low latency for users worldwide"** → CloudFront. ([Amazon CloudFront](/docs/edge/cloudfront)) - **"Only allow access to the S3 content through CloudFront"** → origin access control (OAC) and a bucket policy. ([Amazon CloudFront](/docs/edge/cloudfront)) - **"Origin in a private subnet without public exposure"** → CloudFront VPC origin. ([Amazon CloudFront](/docs/edge/cloudfront)) - **"Block users from certain countries"** → CloudFront geo restriction. ([Amazon CloudFront](/docs/edge/cloudfront)) - **"Users see old content after an update"** → invalidation (or versioned file names). ([Amazon CloudFront](/docs/edge/cloudfront)) - **"Paid content for many files per user"** → signed cookies. **"One file"** → signed URL. ([Amazon CloudFront](/docs/edge/cloudfront)) - **"Reduce CloudFront cost, users only in North America and Europe"** → Price Class 100. ([Amazon CloudFront](/docs/edge/cloudfront)) - **"High availability between two origins"** → origin group (origin failover). ([Amazon CloudFront](/docs/edge/cloudfront)) - **"Static content everywhere vs dynamic content in a few Regions"** → CloudFront vs S3 CRR. ([Amazon CloudFront](/docs/edge/cloudfront)) - **"Static IP addresses", "two IPs to allow-list", "IP addresses can't change"** → Global Accelerator. ([AWS Global Accelerator](/docs/edge/global-accelerator)) - **"UDP", "gaming", "VoIP", "IoT MQTT"** → Global Accelerator (CloudFront is for HTTP). ([AWS Global Accelerator](/docs/edge/global-accelerator)) - **"Fast regional failover, not affected by DNS caching"** → Global Accelerator. ([AWS Global Accelerator](/docs/edge/global-accelerator)) - **"Cache content at the edge"** → CloudFront, not Global Accelerator. ([AWS Global Accelerator](/docs/edge/global-accelerator)) - **"Shift a percentage of traffic between Regions without DNS changes"** → traffic dials. ([AWS Global Accelerator](/docs/edge/global-accelerator)) - **"Lightweight, millions of requests per second, change headers, redirect URLs, normalize cache keys"** → CloudFront Functions. ([Edge functions](/docs/edge/edge-functions)) - **"Needs the AWS SDK", "network calls", "request body", "longer processing", "origin request or response"** → Lambda@Edge. ([Edge functions](/docs/edge/edge-functions)) - **"Authenticate users at the edge with a JWT"** → CloudFront Functions (simple check) or Lambda@Edge (complex). ([Edge functions](/docs/edge/edge-functions)) - **"Where do you create Lambda@Edge functions?"** → us-east-1. ([Edge functions](/docs/edge/edge-functions)) ## Application Integration [#application-integration] - **"Decouple", "absorb spikes", "the backend can't keep up"** → SQS between the tiers. ([Application Integration](/docs/integration)) - **"Send one message to many receivers"** → SNS (often SNS + SQS fan-out). ([Application Integration](/docs/integration)) - **"Real-time streaming", "clickstream", "IoT data", "replay"** → Kinesis Data Streams. ([Application Integration](/docs/integration)) - **"Load streaming data into S3 or Redshift with no code"** → Amazon Data Firehose. ([Application Integration](/docs/integration)) - **"Migrate an app that uses MQTT, AMQP or JMS without rewriting it"** → Amazon MQ. ([Application Integration](/docs/integration)) - **"React to an event in an AWS service", "cron job"** → EventBridge. ([Application Integration](/docs/integration)) - **"Orchestrate several Lambda functions with retries and human approval"** → Step Functions. ([Application Integration](/docs/integration)) - **"Decouple tiers", "buffer requests", "handle traffic spikes"** → SQS. ([Amazon SQS](/docs/integration/sqs)) - **"Scale workers on the number of messages waiting"** → Auto Scaling on `ApproximateNumberOfMessages` (or backlog per instance). ([Amazon SQS](/docs/integration/sqs)) - **"Messages are processed twice"** → visibility timeout too short; raise it or call `ChangeMessageVisibility`. ([Amazon SQS](/docs/integration/sqs)) - **"Reduce empty responses and API costs"** → long polling (`WaitTimeSeconds` up to 20). ([Amazon SQS](/docs/integration/sqs)) - **"Let S3 or SNS send to a queue"**, **"cross-account access"** → SQS access policy. ([Amazon SQS](/docs/integration/sqs)) - **"Messages larger than 1 MiB"** → S3 plus a pointer (Extended Client Library). ([Amazon SQS](/docs/integration/sqs)) - **"Keep messages up to 14 days"** → set the retention period. ([Amazon SQS](/docs/integration/sqs)) - **"Order must be preserved", "no duplicates"** → SQS FIFO (message group ID, deduplication ID). ([SQS FIFO and patterns](/docs/integration/sqs-fifo-patterns)) - **"FIFO throughput"** → 300 msg/s, or 3,000 with batching (higher with high throughput mode). ([SQS FIFO and patterns](/docs/integration/sqs-fifo-patterns)) - **"Messages that fail repeatedly block the queue"** → dead-letter queue with `maxReceiveCount`. ([SQS FIFO and patterns](/docs/integration/sqs-fifo-patterns)) - **"Delay processing of new messages for a few minutes"** → delay queue (up to 15 minutes). ([SQS FIFO and patterns](/docs/integration/sqs-fifo-patterns)) - **"Database can't keep up with writes during spikes, don't lose any"** → SQS as a write buffer. ([SQS FIFO and patterns](/docs/integration/sqs-fifo-patterns)) - **"Notify many receivers of one event", "pub/sub"** → SNS topic. ([Amazon SNS](/docs/integration/sns)) - **"Email or SMS when a CloudWatch alarm fires"** → CloudWatch alarm → SNS. ([Amazon SNS](/docs/integration/sns)) - **"Mobile push notifications"** → SNS. ([Amazon SNS](/docs/integration/sns)) - **"Allow S3 (or another account) to publish to the topic"** → SNS access policy. ([Amazon SNS](/docs/integration/sns)) - **"One event, processed independently by several services"** → SNS + SQS fan-out. ([SNS fan-out and filtering](/docs/integration/sns-fan-out)) - **"Send the same S3 event to several queues"** → S3 → SNS → SQS queues. ([SNS fan-out and filtering](/docs/integration/sns-fan-out)) - **"Fan-out with ordering and deduplication"** → SNS FIFO + SQS FIFO. ([SNS fan-out and filtering](/docs/integration/sns-fan-out)) - **"Each subscriber should only get some messages"** → SNS filter policies. ([SNS fan-out and filtering](/docs/integration/sns-fan-out)) - **"Store all messages from a topic in S3"** → SNS → Data Firehose → S3. ([SNS fan-out and filtering](/docs/integration/sns-fan-out)) - **"Queue doesn't receive messages from the topic"** → the queue's access policy must allow SNS. ([SNS fan-out and filtering](/docs/integration/sns-fan-out)) - **"Real-time streaming", "clickstream", "IoT telemetry", "process in real time", "replay"** → Kinesis Data Streams. ([Kinesis and Data Firehose](/docs/integration/kinesis)) - **"Several applications must read the same stream"** → Kinesis Data Streams (enhanced fan-out for many consumers). ([Kinesis and Data Firehose](/docs/integration/kinesis)) - **"Order per device or user"** → same partition key → same shard. ([Kinesis and Data Firehose](/docs/integration/kinesis)) - **"Load streaming data into S3, Redshift, OpenSearch or Splunk with the least effort"** → Data Firehose. ([Kinesis and Data Firehose](/docs/integration/kinesis)) - **"Convert incoming JSON to Parquet before S3"** → Firehose format conversion (or Lambda transformation). ([Kinesis and Data Firehose](/docs/integration/kinesis)) - **"Near real time is fine (about a minute)"** → Firehose; **"milliseconds"** → Data Streams. ([Kinesis and Data Firehose](/docs/integration/kinesis)) - **"Unpredictable stream throughput, no shard management"** → on-demand mode. ([Kinesis and Data Firehose](/docs/integration/kinesis)) - **"Decouple and buffer work"** → SQS. **"Notify many systems"** → SNS. **"Real-time analytics on a stream"** → Kinesis. ([SQS vs SNS vs Kinesis](/docs/integration/sqs-sns-kinesis)) - **"Replay messages from yesterday"** → Kinesis (or an SNS FIFO topic archive, or EventBridge archive); SQS deletes processed messages. ([SQS vs SNS vs Kinesis](/docs/integration/sqs-sns-kinesis)) - **"Several consumers each need every record"** → SNS fan-out or Kinesis, not one SQS queue. ([SQS vs SNS vs Kinesis](/docs/integration/sqs-sns-kinesis)) - **"No capacity planning at all"** → SQS or SNS (or Kinesis on-demand). ([SQS vs SNS vs Kinesis](/docs/integration/sqs-sns-kinesis)) - **"Migrate an on-premises app using MQTT, AMQP, STOMP, OpenWire or JMS without changing code"** → Amazon MQ. ([Amazon MQ](/docs/integration/amazon-mq)) - **"ActiveMQ or RabbitMQ in the cloud, managed"** → Amazon MQ. ([Amazon MQ](/docs/integration/amazon-mq)) - **"New cloud-native application, massive scale"** → SQS / SNS rather than Amazon MQ. ([Amazon MQ](/docs/integration/amazon-mq)) - **"High availability for Amazon MQ"** → active/standby across two AZs (ActiveMQ) or a three-node cluster (RabbitMQ). ([Amazon MQ](/docs/integration/amazon-mq)) - **"Run a function on a schedule", "cron in AWS"** → EventBridge schedule (or EventBridge Scheduler). ([Amazon EventBridge](/docs/integration/eventbridge)) - **"React when an EC2 instance stops", "when an S3 object is created"** → EventBridge rule. ([Amazon EventBridge](/docs/integration/eventbridge)) - **"Alert when someone calls a specific API"** → CloudTrail + EventBridge rule + SNS. ([Amazon EventBridge](/docs/integration/eventbridge)) - **"Receive events from a SaaS application"** → partner event bus. ([Amazon EventBridge](/docs/integration/eventbridge)) - **"Centralize events from all accounts"** → event bus resource-based policy (allow the organization). ([Amazon EventBridge](/docs/integration/eventbridge)) - **"Reprocess past events after a bug fix"** → archive and replay. ([Amazon EventBridge](/docs/integration/eventbridge)) - **"Generate code bindings for event structures"** → schema registry. ([Amazon EventBridge](/docs/integration/eventbridge)) - **"Orchestrate several Lambda functions", "visual workflow", "retries and error handling between steps"** → Step Functions. ([AWS Step Functions](/docs/integration/step-functions)) - **"Workflow needs human approval"** → Step Functions (task token / callback). ([AWS Step Functions](/docs/integration/step-functions)) - **"Long-running workflow, up to a year, exactly once"** → Standard workflow. ([AWS Step Functions](/docs/integration/step-functions)) - **"High-volume, short (under 5 minutes) event processing"** → Express workflow. ([AWS Step Functions](/docs/integration/step-functions)) - **"Transfer data from Salesforce (or another SaaS app) to S3 or Redshift with no code"** → Amazon AppFlow. ([Amazon AppFlow](/docs/integration/appflow)) - **"SaaS data transfer that must not cross the public internet"** → AppFlow with PrivateLink. ([Amazon AppFlow](/docs/integration/appflow)) - **"Send transactional or marketing email from an application"** → SES. ([Amazon SES and Pinpoint](/docs/integration/ses-pinpoint)) - **"Simple notifications to subscribers (email, SMS)"** → SNS. ([Amazon SES and Pinpoint](/docs/integration/ses-pinpoint)) - **"Marketing campaigns with segments and templates"** → was Pinpoint; now Amazon Connect and End User Messaging. ([Amazon SES and Pinpoint](/docs/integration/ses-pinpoint)) ## Containers [#containers] - **"Run Docker containers on AWS"** → ECS (or EKS if they already use Kubernetes). ([Containers](/docs/containers)) - **"Containers with no servers to manage"** → Fargate. ([Containers](/docs/containers)) - **"Already using Kubernetes", "cloud-agnostic"** → EKS. ([Containers](/docs/containers)) - **"Store Docker images privately"** → ECR. ([Containers](/docs/containers)) - **"Run containers without managing servers"** → ECS on Fargate. ([Amazon ECS](/docs/containers/ecs)) - **"Need specific instance types, custom AMIs, or full control of hosts"** → EC2 launch type (or Managed Instances for specific types without host management). ([Amazon ECS](/docs/containers/ecs)) - **"Give one container access to S3 and another to DynamoDB"** → separate ECS task roles. ([Amazon ECS](/docs/containers/ecs)) - **"ECS tasks need to pull images from ECR and write logs"** → instance profile (EC2) or task execution role. ([Amazon ECS](/docs/containers/ecs)) - **"Several tasks on one instance behind a load balancer"** → ALB with dynamic host port mapping. ([Amazon ECS](/docs/containers/ecs)) - **"Persistent storage shared by Fargate tasks across AZs"** → EFS. ([Amazon ECS](/docs/containers/ecs)) - **"Scale the number of ECS tasks on CPU, memory or ALB requests"** → ECS Service Auto Scaling. ([ECS scaling and patterns](/docs/containers/ecs-scaling-patterns)) - **"Add EC2 instances automatically when tasks can't be placed"** → ECS capacity provider with an Auto Scaling group. ([ECS scaling and patterns](/docs/containers/ecs-scaling-patterns)) - **"Run a container when a file lands in S3"** → S3 event → EventBridge rule → ECS task. ([ECS scaling and patterns](/docs/containers/ecs-scaling-patterns)) - **"Run a container every hour"** → EventBridge schedule → ECS task (Fargate). ([ECS scaling and patterns](/docs/containers/ecs-scaling-patterns)) - **"Process messages from a queue with containers, scaling with the backlog"** → ECS service + SQS + Service Auto Scaling. ([ECS scaling and patterns](/docs/containers/ecs-scaling-patterns)) - **"Notify when a container stops unexpectedly"** → ECS task state change event → EventBridge → SNS. ([ECS scaling and patterns](/docs/containers/ecs-scaling-patterns)) - **"Private Docker registry on AWS"** → Amazon ECR. ([Amazon ECR](/docs/containers/ecr)) - **"ECS tasks can't pull the image"** → IAM permissions (instance profile or task execution role). ([Amazon ECR](/docs/containers/ecr)) - **"Scan container images for vulnerabilities"** → ECR image scanning (enhanced = Amazon Inspector). ([Amazon ECR](/docs/containers/ecr)) - **"Delete old images automatically"** → ECR lifecycle policy. ([Amazon ECR](/docs/containers/ecr)) - **"Images available in another Region for DR"** → ECR cross-Region replication. ([Amazon ECR](/docs/containers/ecr)) - **"Already using Kubernetes", "migrate Kubernetes workloads", "cloud-agnostic containers"** → EKS. ([Amazon EKS](/docs/containers/eks)) - **"Kubernetes without managing nodes"** → EKS on Fargate (or EKS Auto Mode). ([Amazon EKS](/docs/containers/eks)) - **"Nodes managed by AWS, On-Demand or Spot"** → managed node groups. ([Amazon EKS](/docs/containers/eks)) - **"Persistent storage for EKS pods on Fargate"** → EFS. ([Amazon EKS](/docs/containers/eks)) - **"Manage on-premises containers with the ECS control plane"** → ECS Anywhere. ([Amazon EKS](/docs/containers/eks)) - **"Kubernetes in our own data centre, supported by AWS, even disconnected"** → EKS Anywhere. ([Amazon EKS](/docs/containers/eks)) - **"Same Kubernetes as EKS, self-managed anywhere"** → EKS Distro. ([Amazon EKS](/docs/containers/eks)) ## Serverless [#serverless] - **"No servers to manage", "pay only for what you use", "scales automatically"** → a serverless design (Lambda, API Gateway, DynamoDB, S3, Fargate). ([Serverless](/docs/serverless)) - **"Serverless REST API"** → API Gateway + Lambda (+ DynamoDB). ([Serverless](/docs/serverless)) - **"Run code in response to events without managing servers"** → Lambda. ([AWS Lambda](/docs/serverless/lambda)) - **"Process files as they're uploaded to S3"** → S3 event → Lambda. ([AWS Lambda](/docs/serverless/lambda)) - **"Run a script every hour without a server"** → EventBridge schedule → Lambda. ([AWS Lambda](/docs/serverless/lambda)) - **"Function needs more CPU"** → increase its memory. ([AWS Lambda](/docs/serverless/lambda)) - **"Run a Docker image as a function"** → Lambda container image (if it implements the Runtime API); otherwise ECS/Fargate. ([AWS Lambda](/docs/serverless/lambda)) - **"Function takes longer than 15 minutes"** → not Lambda (ECS/Fargate, Batch, or split the work with Step Functions). Note the new 30-minute limit, but exam questions still use 15. ([Lambda limits and concurrency](/docs/serverless/lambda-limits-concurrency)) - **"One function's traffic throttles other functions"** → reserved concurrency on the critical ones. ([Lambda limits and concurrency](/docs/serverless/lambda-limits-concurrency)) - **"Limit a function to protect a database"** → reserved concurrency as a cap. ([Lambda limits and concurrency](/docs/serverless/lambda-limits-concurrency)) - **"First requests are slow", "latency-sensitive", "no cold starts"** → provisioned concurrency (or SnapStart for Java, Python, .NET). ([Lambda limits and concurrency](/docs/serverless/lambda-limits-concurrency)) - **"Throttled synchronous call"** → HTTP 429. **"Failed asynchronous events"** → retries, then DLQ or on-failure destination. ([Lambda limits and concurrency](/docs/serverless/lambda-limits-concurrency)) - **"Need more than 1,000 concurrent executions"** → request a quota increase. ([Lambda limits and concurrency](/docs/serverless/lambda-limits-concurrency)) - **"Payload over 6 MB"** → put the data in S3 and pass a reference. ([Lambda limits and concurrency](/docs/serverless/lambda-limits-concurrency)) - **"Lambda can't connect to a private RDS database"** → configure the function with the VPC, subnets and security groups. ([Lambda networking and RDS](/docs/serverless/lambda-networking)) - **"Lambda in a VPC can't reach the internet"** → private subnet + NAT gateway (or VPC endpoints for AWS services). ([Lambda networking and RDS](/docs/serverless/lambda-networking)) - **"Too many database connections from Lambda"** → RDS Proxy (and the function must be in the VPC). ([Lambda networking and RDS](/docs/serverless/lambda-networking)) - **"Run code when a row is inserted in RDS PostgreSQL or Aurora MySQL"** → invoke Lambda from the database. ([Lambda networking and RDS](/docs/serverless/lambda-networking)) - **"Be notified when a DB instance is stopped or a snapshot completes"** → RDS event notifications to SNS or EventBridge. ([Lambda networking and RDS](/docs/serverless/lambda-networking)) - **"Serverless REST API"** → API Gateway + Lambda. ([Amazon API Gateway](/docs/serverless/api-gateway)) - **"Add API keys, throttling, caching, authentication in front of an existing HTTP backend"** → API Gateway HTTP integration. ([Amazon API Gateway](/docs/serverless/api-gateway)) - **"Send requests straight to SQS, Kinesis or Step Functions without code"** → API Gateway AWS service integration. ([Amazon API Gateway](/docs/serverless/api-gateway)) - **"Users around the world"** → edge-optimized; **"same Region"** → Regional; **"only from inside the VPC"** → private endpoint. ([Amazon API Gateway](/docs/serverless/api-gateway)) - **"Authenticate mobile app users"** → Cognito user pools; **"internal AWS clients"** → IAM; **"custom token logic"** → Lambda authorizer. ([Amazon API Gateway](/docs/serverless/api-gateway)) - **"Custom domain on an edge-optimized API"** → ACM certificate in us-east-1. ([Amazon API Gateway](/docs/serverless/api-gateway)) - **"API returns 429"** → throttling limits; **"504 after 29 seconds"** → integration timeout. ([Amazon API Gateway](/docs/serverless/api-gateway)) - **"Build and deploy a full-stack web or mobile app quickly, with auth, storage and APIs"** → AWS Amplify. ([AWS Amplify and Device Farm](/docs/serverless/amplify)) - **"Host a static or Next.js site with CI/CD from a Git repository"** → Amplify Hosting. ([AWS Amplify and Device Farm](/docs/serverless/amplify)) - **"Test a mobile app on many real devices"** → AWS Device Farm. ([AWS Amplify and Device Farm](/docs/serverless/amplify)) - **"Share serverless applications across teams or accounts and deploy them easily"** → Serverless Application Repository. ([Serverless Application Repository](/docs/serverless/serverless-application-repository)) - **"Find and deploy a ready-made serverless app"** → Serverless Application Repository. ([Serverless Application Repository](/docs/serverless/serverless-application-repository)) ## Analytics [#analytics] - **"Serverless", "least operational overhead", "query data in S3"** → Athena (often with Glue and QuickSight). ([Analytics](/docs/analytics)) - **"Data warehouse", "OLAP", "complex analytical queries"** → Redshift. ([Analytics](/docs/analytics)) - **"Convert to a columnar format to cut cost"** → Glue job to Parquet or ORC, then Athena. ([Analytics](/docs/analytics)) - **"Streaming data"** → Kinesis or MSK to ingest, Flink to process, Firehose to load. ([Analytics](/docs/analytics)) - **"Analyse data in S3 using serverless SQL"** → Athena. ([Amazon Athena](/docs/analytics/athena)) - **"Query VPC Flow Logs, ELB logs, CloudTrail logs ad hoc"** → Athena. ([Amazon Athena](/docs/analytics/athena)) - **"Reduce Athena cost or improve performance"** → columnar formats (Parquet, ORC), compression, partitioning, larger files. ([Amazon Athena](/docs/analytics/athena)) - **"Run SQL across DynamoDB, RDS and on-premises data without moving it"** → Athena Federated Query. ([Amazon Athena](/docs/analytics/athena)) - **"Dashboards on Athena results"** → QuickSight. ([Amazon Athena](/docs/analytics/athena)) - **"Data warehouse", "OLAP", "BI on petabytes", "complex joins and aggregations"** → Redshift. ([Amazon Redshift](/docs/analytics/redshift)) - **"Query S3 data from Redshift without loading it"** → Redshift Spectrum. ([Amazon Redshift](/docs/analytics/redshift)) - **"Disaster recovery for Redshift in another Region"** → automated cross-Region snapshot copy. ([Amazon Redshift](/docs/analytics/redshift)) - **"Load data into Redshift efficiently"** → `COPY` from S3 (large batches), or Firehose for streams. ([Amazon Redshift](/docs/analytics/redshift)) - **"COPY traffic must not leave the VPC"** → enhanced VPC routing. ([Amazon Redshift](/docs/analytics/redshift)) - **"Unpredictable, occasional warehouse workloads"** → Redshift Serverless. ([Amazon Redshift](/docs/analytics/redshift)) - **"Search any field", "full-text search", "partial matches"** → OpenSearch. ([Amazon OpenSearch Service](/docs/analytics/opensearch)) - **"Make DynamoDB data searchable"** → DynamoDB Streams + Lambda (or OpenSearch Ingestion) to OpenSearch. ([Amazon OpenSearch Service](/docs/analytics/opensearch)) - **"Real-time log analytics and dashboards"** → CloudWatch Logs subscription filter to OpenSearch. ([Amazon OpenSearch Service](/docs/analytics/opensearch)) - **"Near real time, managed, no code"** → through Firehose. **"Real time"** → through Lambda. ([Amazon OpenSearch Service](/docs/analytics/opensearch)) - **"Elasticsearch on AWS"** → Amazon OpenSearch Service. ([Amazon OpenSearch Service](/docs/analytics/opensearch)) - **"Hadoop", "Spark", "Hive", "HBase", "big data cluster"** → EMR. ([Amazon EMR](/docs/analytics/emr)) - **"Cheapest compute for EMR that can be interrupted"** → Spot task nodes. ([Amazon EMR](/docs/analytics/emr)) - **"Don't lose data if nodes are reclaimed"** → keep core nodes On-Demand (or Reserved); use Spot for task nodes. ([Amazon EMR](/docs/analytics/emr)) - **"Run a nightly batch job and pay only while it runs"** → transient cluster (or EMR Serverless). ([Amazon EMR](/docs/analytics/emr)) - **"Spark without managing clusters"** → EMR Serverless (or Glue for ETL). ([Amazon EMR](/docs/analytics/emr)) - **"Business intelligence dashboards", "visualize data", "serverless BI"** → QuickSight. ([Amazon QuickSight](/docs/analytics/quicksight)) - **"Dashboards on data in S3"** → Athena + QuickSight. ([Amazon QuickSight](/docs/analytics/quicksight)) - **"Users should see only some columns or rows"** → QuickSight Enterprise CLS or RLS (or Lake Formation for the data lake). ([Amazon QuickSight](/docs/analytics/quicksight)) - **"Fast dashboards with in-memory data"** → import into SPICE. ([Amazon QuickSight](/docs/analytics/quicksight)) - **"Serverless ETL", "transform data for analytics"** → Glue. ([AWS Glue](/docs/analytics/glue)) - **"Convert CSV to Parquet (or ORC) to reduce Athena cost"** → Glue ETL job. ([AWS Glue](/docs/analytics/glue)) - **"Discover data and build a schema automatically"** → Glue crawler + Data Catalog. ([AWS Glue](/docs/analytics/glue)) - **"Central metadata store for Athena, Redshift Spectrum and EMR"** → Glue Data Catalog. ([AWS Glue](/docs/analytics/glue)) - **"Don't reprocess data already handled"** → job bookmarks. ([AWS Glue](/docs/analytics/glue)) - **"Clean data visually without code"** → Glue DataBrew. ([AWS Glue](/docs/analytics/glue)) - **"Build a data lake quickly"** → Lake Formation. ([AWS Lake Formation](/docs/analytics/lake-formation)) - **"Centrally manage fine-grained (column, row, cell-level) access to data in the data lake"** → Lake Formation permissions. ([AWS Lake Formation](/docs/analytics/lake-formation)) - **"Share data lake tables across accounts with fine-grained control"** → Lake Formation (cross-account sharing, LF-Tags). ([AWS Lake Formation](/docs/analytics/lake-formation)) - **"De-duplicate records in the data lake"** → Lake Formation / Glue ML transforms (FindMatches). ([AWS Lake Formation](/docs/analytics/lake-formation)) - **"Real-time analytics or transformations on a stream"** → Managed Service for Apache Flink. ([Managed Flink and Amazon MSK](/docs/analytics/flink-msk)) - **"Kafka", "migrate an existing Kafka cluster", "Kafka without managing servers"** → Amazon MSK (MSK Serverless). ([Managed Flink and Amazon MSK](/docs/analytics/flink-msk)) - **"Read from MSK"** → Flink, Glue streaming ETL, Lambda, or apps on EC2/ECS/EKS. ([Managed Flink and Amazon MSK](/docs/analytics/flink-msk)) - **"Kinesis Data Analytics"** in an old question → Managed Service for Apache Flink. ([Managed Flink and Amazon MSK](/docs/analytics/flink-msk)) - **"Serverless pipeline: collect in real time, transform, query with SQL, dashboards"** → Kinesis Data Streams → Firehose (+ Lambda) → S3 → Athena → QuickSight. ([Big data ingestion pipeline](/docs/analytics/big-data-pipeline)) - **"Near real-time delivery to S3"** → Firehose. **"Real-time ingestion"** → Kinesis Data Streams. ([Big data ingestion pipeline](/docs/analytics/big-data-pipeline)) - **"Transform records in flight with Firehose"** → a Lambda transformation. ([Big data ingestion pipeline](/docs/analytics/big-data-pipeline)) - **"Subscribe to third-party datasets", "buy data from providers"** → AWS Data Exchange. ([Data Exchange, Data Pipeline and Kinesis Video Streams](/docs/analytics/data-exchange-data-pipeline)) - **"Schedule data movement and processing"** → today Glue, Step Functions or MWAA; Data Pipeline only for existing customers. ([Data Exchange, Data Pipeline and Kinesis Video Streams](/docs/analytics/data-exchange-data-pipeline)) - **"Stream video from cameras for ML analysis or playback"** → Kinesis Video Streams. ([Data Exchange, Data Pipeline and Kinesis Video Streams](/docs/analytics/data-exchange-data-pipeline)) ## Machine Learning [#machine-learning] - **"Detect objects, faces, unsafe content in images or video"** → Rekognition. ([Machine Learning](/docs/ml)) - **"Extract text, forms, tables from scanned documents"** → Textract. ([Machine Learning](/docs/ml)) - **"Speech to text", "subtitles", "call transcripts"** → Transcribe. **"Text to speech", "app that talks"** → Polly. ([Machine Learning](/docs/ml)) - **"Translate content for international users"** → Translate. ([Machine Learning](/docs/ml)) - **"Sentiment", "key phrases", "entities in text"** → Comprehend; **"clinical text", "PHI"** → Comprehend Medical. ([Machine Learning](/docs/ml)) - **"Chatbot"** → Lex. **"Call center"** → Connect. ([Machine Learning](/docs/ml)) - **"Build, train and deploy custom ML models"** → SageMaker AI. ([Machine Learning](/docs/ml)) - **"Detect objects, scenes, faces, celebrities in images or video"** → Rekognition. ([Rekognition and Textract](/docs/ml/vision-documents)) - **"Moderate user-generated images and videos"** → Rekognition content moderation (+ A2I for human review). ([Rekognition and Textract](/docs/ml/vision-documents)) - **"Human review of low-confidence ML results"** → Amazon Augmented AI (A2I). ([Rekognition and Textract](/docs/ml/vision-documents)) - **"Extract text and data from scanned forms, tables, invoices, IDs"** → Textract. ([Rekognition and Textract](/docs/ml/vision-documents)) - **"Speech to text", "subtitles", "transcribe calls"** → Transcribe. **"Remove PII from transcripts"** → Transcribe redaction. ([Transcribe, Polly, Translate and Comprehend](/docs/ml/speech-language)) - **"Text to speech"** → Polly. **"Customise pronunciation"** → lexicons. **"Whisper, emphasis, breathing"** → SSML. ([Transcribe, Polly, Translate and Comprehend](/docs/ml/speech-language)) - **"Translate a website or app"** → Translate. ([Transcribe, Polly, Translate and Comprehend](/docs/ml/speech-language)) - **"Sentiment analysis", "extract entities or key phrases"** → Comprehend. ([Transcribe, Polly, Translate and Comprehend](/docs/ml/speech-language)) - **"Medical notes", "detect PHI"** → Comprehend Medical. ([Transcribe, Polly, Translate and Comprehend](/docs/ml/speech-language)) - **"Chatbot", "voice bot", "conversational interface"** → Lex. ([Lex, Connect and Kendra](/docs/ml/lex-connect-kendra)) - **"Cloud contact center", "call center"** → Connect (with Lex for self-service). ([Lex, Connect and Kendra](/docs/ml/lex-connect-kendra)) - **"Search documents with natural language questions"** → Kendra. ([Lex, Connect and Kendra](/docs/ml/lex-connect-kendra)) - **"Build, train and deploy custom ML models", "data scientists"** → SageMaker AI. ([SageMaker AI and Personalize](/docs/ml/sagemaker-personalize)) - **"Recommendations"** → Personalize (out of scope, but recognise it). ([SageMaker AI and Personalize](/docs/ml/sagemaker-personalize)) ## Monitoring & Governance [#monitoring--governance] - **"Monitor performance", "metrics", "alarm when CPU is high", "logs"** → CloudWatch. ([Monitoring & Governance](/docs/management)) - **"Who deleted the resource?", "audit API calls"** → CloudTrail. ([Monitoring & Governance](/docs/management)) - **"Is the resource compliant?", "track configuration changes over time"** → AWS Config. ([Monitoring & Governance](/docs/management)) - **"Monitor RAM (memory) or disk space of EC2"** → custom metric, usually through the CloudWatch agent. ([CloudWatch metrics](/docs/management/cloudwatch-metrics)) - **"Metrics every second"** → high-resolution custom metrics. **"EC2 metrics every minute"** → detailed monitoring. ([CloudWatch metrics](/docs/management/cloudwatch-metrics)) - **"Send CloudWatch metrics to a third-party tool or S3 in near real time"** → metric streams. ([CloudWatch metrics](/docs/management/cloudwatch-metrics)) - **"Analyse or search logs with queries"** → Logs Insights. ([CloudWatch Logs](/docs/management/cloudwatch-logs)) - **"Logs to S3 in batch"** → export (`CreateExportTask`, up to 12 hours). **"Real time / near real time"** → subscription filter to Kinesis, Firehose or Lambda. ([CloudWatch Logs](/docs/management/cloudwatch-logs)) - **"Centralize logs from many accounts and Regions"** → subscriptions to one Kinesis stream (cross-account destination), then Firehose to S3. ([CloudWatch Logs](/docs/management/cloudwatch-logs)) - **"Collect RAM, disk, processes from EC2 or on premises"** → CloudWatch unified agent. ([CloudWatch Logs](/docs/management/cloudwatch-logs)) - **"No logs from EC2 in CloudWatch"** → install the agent and check the instance role permissions. ([CloudWatch Logs](/docs/management/cloudwatch-logs)) - **"Automatically recover an EC2 instance on hardware failure, keeping its IP"** → alarm on `StatusCheckFailed_System` with the recover action (or simplified automatic recovery). ([CloudWatch alarms](/docs/management/cloudwatch-alarms)) - **"Reduce alarm noise", "alert only when several conditions are true"** → composite alarm. ([CloudWatch alarms](/docs/management/cloudwatch-alarms)) - **"Alarm on errors in logs"** → metric filter + alarm. ([CloudWatch alarms](/docs/management/cloudwatch-alarms)) - **"Test an alarm's notification"** → `set-alarm-state`. ([CloudWatch alarms](/docs/management/cloudwatch-alarms)) - **"Monitor latency and packet loss to on premises over Direct Connect or VPN, no agents"** → Network Synthetic Monitor. ([CloudWatch alarms](/docs/management/cloudwatch-alarms)) - **"Metrics and logs for ECS, EKS, Fargate containers"** → Container Insights. ([CloudWatch Insights](/docs/management/cloudwatch-insights)) - **"Troubleshoot Lambda performance, cold starts, memory"** → Lambda Insights. ([CloudWatch Insights](/docs/management/cloudwatch-insights)) - **"Top-N", "heaviest users", "top talkers", "which IP generates the most traffic or errors"** → Contributor Insights. ([CloudWatch Insights](/docs/management/cloudwatch-insights)) - **"Automatic dashboards for a .NET or SQL Server application on EC2"** → Application Insights. ([CloudWatch Insights](/docs/management/cloudwatch-insights)) - **"Who deleted / modified the resource?", "audit API calls"** → CloudTrail. ([AWS CloudTrail](/docs/management/cloudtrail)) - **"Keep CloudTrail logs longer than 90 days and analyse them"** → trail to S3 + Athena. ([AWS CloudTrail](/docs/management/cloudtrail)) - **"Log S3 object-level operations (GetObject, PutObject)"** → enable **data events**. ([AWS CloudTrail](/docs/management/cloudtrail)) - **"Detect unusual API activity", "burst of IAM actions"** → CloudTrail Insights. ([AWS CloudTrail](/docs/management/cloudtrail)) - **"Alert when a specific API call happens"** → CloudTrail + EventBridge rule + SNS. ([AWS CloudTrail](/docs/management/cloudtrail)) - **"Audit all accounts in an organization"** → organization trail. ([AWS CloudTrail](/docs/management/cloudtrail)) - **"Is this resource compliant?", "track configuration changes over time"** → AWS Config. ([AWS Config](/docs/management/config)) - **"Automatically fix non-compliant resources"** → Config rule + remediation with SSM Automation. ([AWS Config](/docs/management/config)) - **"Notify when a resource becomes non-compliant"** → Config + EventBridge (or SNS). ([AWS Config](/docs/management/config)) - **"Compliance across accounts and Regions"** → Config aggregator. ([AWS Config](/docs/management/config)) - **"Custom compliance check"** → custom Config rule with Lambda. ([AWS Config](/docs/management/config)) - **"Infrastructure as code", "repeatable environments", "re-create the same infrastructure"** → CloudFormation. ([AWS CloudFormation](/docs/management/cloudformation)) - **"Let users deploy stacks without giving them permissions on the resources"** → CloudFormation service role + `iam:PassRole`. ([AWS CloudFormation](/docs/management/cloudformation)) - **"Deploy the same stack to many accounts and Regions"** → StackSets. ([AWS CloudFormation](/docs/management/cloudformation)) - **"Shell access without SSH, bastion hosts, keys or port 22"** → Session Manager. ([AWS Systems Manager](/docs/management/systems-manager)) - **"Run a script on many instances at once"** → Run Command. ([AWS Systems Manager](/docs/management/systems-manager)) - **"Patch EC2 and on-premises servers, compliance report"** → Patch Manager (+ Maintenance Windows). ([AWS Systems Manager](/docs/management/systems-manager)) - **"Automate routine tasks: restart, AMI, snapshot"** → SSM Automation runbooks. ([AWS Systems Manager](/docs/management/systems-manager)) - **"Instance doesn't appear in Systems Manager"** → check the SSM Agent and the instance's IAM role (and network access to SSM endpoints). ([AWS Systems Manager](/docs/management/systems-manager)) - **"Trace requests across microservices", "find the bottleneck", "service map", "debug distributed applications"** → AWS X-Ray. ([AWS X-Ray](/docs/management/x-ray)) - **"Troubleshoot latency in a serverless application end to end"** → X-Ray (with Lambda active tracing). ([AWS X-Ray](/docs/management/x-ray)) - **"Be notified of AWS maintenance or issues that affect resources in my account"** → AWS Health Dashboard (your account health). ([AWS Health Dashboard](/docs/management/health-dashboard)) - **"Automatically respond to an AWS Health event"** → AWS Health events in EventBridge. ([AWS Health Dashboard](/docs/management/health-dashboard)) - **"Health events for all accounts in the organization"** → organizational view. ([AWS Health Dashboard](/docs/management/health-dashboard)) - **"Let users self-provision only approved, compliant resources", "catalog of approved products"** → AWS Service Catalog. ([Service Catalog, Proton and License Manager](/docs/management/service-catalog-proton-license-manager)) - **"Users launch products without permissions on the underlying services"** → Service Catalog launch constraint. ([Service Catalog, Proton and License Manager](/docs/management/service-catalog-proton-license-manager)) - **"Track software licences, BYOL, prevent licence overuse"** → AWS License Manager. ([Service Catalog, Proton and License Manager](/docs/management/service-catalog-proton-license-manager)) - **"Prometheus-compatible", "PromQL", "monitor container metrics at scale without managing servers"** → Amazon Managed Service for Prometheus. ([Managed Grafana and Managed Service for Prometheus](/docs/management/managed-grafana-prometheus)) - **"Grafana dashboards", "visualize metrics from several sources, managed"** → Amazon Managed Grafana. ([Managed Grafana and Managed Service for Prometheus](/docs/management/managed-grafana-prometheus)) - **"Already use Prometheus and Grafana on premises, move to AWS with the least operational overhead"** → both managed services. ([Managed Grafana and Managed Service for Prometheus](/docs/management/managed-grafana-prometheus)) ## Security & Encryption [#security--encryption] - **"Encryption" for an AWS service** → almost always KMS. ([Security & Encryption](/docs/security)) - **"The server must never see the plaintext"** → client-side encryption. ([Security & Encryption](/docs/security)) - **"Protect data in transit"** → TLS (HTTPS), with certificates from ACM. ([Security & Encryption](/docs/security)) - **"Encrypt data at rest and audit key usage"** → KMS (+ CloudTrail). ([AWS KMS](/docs/security/kms)) - **"Users outside AWS must encrypt data they send"** → asymmetric KMS key (download the public key). ([AWS KMS](/docs/security/kms)) - **"Share an encrypted snapshot or AMI with another account"** → customer managed key + key policy + share. ([AWS KMS](/docs/security/kms)) - **"Copy an encrypted snapshot to another Region"** → copy and re-encrypt with a key in that Region. ([AWS KMS](/docs/security/kms)) - **"Automatic yearly key rotation"** → enable rotation on a customer managed key. ([AWS KMS](/docs/security/kms)) - **"Encrypt in one Region, decrypt in another without re-encrypting"** → KMS multi-Region keys. ([KMS multi-Region keys and encrypted sharing](/docs/security/kms-multi-region)) - **"Protect specific fields even from database admins, in a global table"** → client-side encryption + multi-Region keys. ([KMS multi-Region keys and encrypted sharing](/docs/security/kms-multi-region)) - **"Replicate SSE-KMS objects"** → enable the KMS option in replication, target key, and an IAM role with decrypt and encrypt permissions. ([KMS multi-Region keys and encrypted sharing](/docs/security/kms-multi-region)) - **"Share an encrypted AMI"** → launch permission + share the KMS key. ([KMS multi-Region keys and encrypted sharing](/docs/security/kms-multi-region)) - **"Dedicated, single-tenant hardware", "you manage the keys", "FIPS 140 Level 3 HSM you control"** → CloudHSM. ([AWS CloudHSM](/docs/security/cloudhsm)) - **"Keys must never be accessible to AWS"** → CloudHSM. ([AWS CloudHSM](/docs/security/cloudhsm)) - **"SSE-C with keys in an HSM", "Oracle TDE", "SSL offload"** → CloudHSM. ([AWS CloudHSM](/docs/security/cloudhsm)) - **"Use CloudHSM keys with S3 or EBS encryption"** → KMS custom key store backed by CloudHSM. ([AWS CloudHSM](/docs/security/cloudhsm)) - **"Store configuration and secrets centrally, encrypted, cheaply"** → Parameter Store (`SecureString`). ([SSM Parameter Store](/docs/security/ssm-parameter-store)) - **"Organise config per environment"** → parameter hierarchy + `GetParametersByPath` + IAM by path. ([SSM Parameter Store](/docs/security/ssm-parameter-store)) - **"Latest AMI ID"** → Parameter Store public parameters. ([SSM Parameter Store](/docs/security/ssm-parameter-store)) - **"Values over 4 KB" or "expiry notifications"** → advanced tier. ([SSM Parameter Store](/docs/security/ssm-parameter-store)) - **"Rotate database credentials automatically"** → Secrets Manager. ([AWS Secrets Manager](/docs/security/secrets-manager)) - **"Store RDS credentials securely, no passwords in code"** → Secrets Manager (with RDS integration). ([AWS Secrets Manager](/docs/security/secrets-manager)) - **"Same secret in several Regions", "DR for secrets"** → multi-Region secrets. ([AWS Secrets Manager](/docs/security/secrets-manager)) - **"Cheapest way to store config and secrets, no rotation needed"** → Parameter Store. ([AWS Secrets Manager](/docs/security/secrets-manager)) - **"Free TLS certificates that renew automatically"** → ACM public certificates (DNS validation). ([AWS Certificate Manager (ACM)](/docs/security/acm)) - **"HTTPS on an ALB, CloudFront or API Gateway"** → ACM certificate. ([AWS Certificate Manager (ACM)](/docs/security/acm)) - **"Certificate for an edge-optimized API or CloudFront"** → ACM in **us-east-1**. ([AWS Certificate Manager (ACM)](/docs/security/acm)) - **"Imported certificate expiring"** → re-import before expiry; monitor with EventBridge expiry events or the Config rule. ([AWS Certificate Manager (ACM)](/docs/security/acm)) - **"TLS certificate on an EC2 instance directly"** → not a standard ACM public certificate (use your own, or the newer exportable certificates). ([AWS Certificate Manager (ACM)](/docs/security/acm)) - **"SQL injection", "cross-site scripting", "block countries", "rate limit by IP"** → AWS WAF. ([WAF, Shield and Firewall Manager](/docs/security/waf-shield-firewall-manager)) - **"WAF on a Network Load Balancer"** → not possible; use Global Accelerator + ALB with WAF for fixed IPs. ([WAF, Shield and Firewall Manager](/docs/security/waf-shield-firewall-manager)) - **"DDoS protection at no cost"** → Shield Standard (automatic). ([WAF, Shield and Firewall Manager](/docs/security/waf-shield-firewall-manager)) - **"DDoS response team", "cost protection", "sophisticated DDoS"** → Shield Advanced. ([WAF, Shield and Firewall Manager](/docs/security/waf-shield-firewall-manager)) - **"Apply WAF rules or security groups across all accounts, including new ones"** → Firewall Manager. ([WAF, Shield and Firewall Manager](/docs/security/waf-shield-firewall-manager)) - **"Protect a web app from DDoS"** → CloudFront (+ WAF rate-based rules) in front, ALB + Auto Scaling behind, Shield Advanced for more. ([DDoS resiliency best practices](/docs/security/ddos-best-practices)) - **"Non-HTTP app needs edge DDoS protection"** → Global Accelerator (+ Shield). ([DDoS resiliency best practices](/docs/security/ddos-best-practices)) - **"Hide the backend"** → put CloudFront, API Gateway or a load balancer in front, and lock down security groups. ([DDoS resiliency best practices](/docs/security/ddos-best-practices)) - **"Detect threats", "compromised instance", "crypto mining", "unusual API calls"** → GuardDuty. ([GuardDuty, Inspector and Macie](/docs/security/guardduty-inspector-macie)) - **"Scan EC2, ECR images or Lambda for vulnerabilities (CVEs)"** → Inspector. ([GuardDuty, Inspector and Macie](/docs/security/guardduty-inspector-macie)) - **"Find PII or sensitive data in S3"** → Macie. ([GuardDuty, Inspector and Macie](/docs/security/guardduty-inspector-macie)) - **"Automate a response to a finding"** → EventBridge rule → Lambda or SNS. ([GuardDuty, Inspector and Macie](/docs/security/guardduty-inspector-macie)) - **"Central view of security findings across accounts", "check against CIS or PCI best practices"** → Security Hub. ([Detective, Security Hub and Artifact](/docs/security/detective-security-hub-artifact)) - **"Investigate the root cause of a GuardDuty finding", "visualize what happened"** → Detective. ([Detective, Security Hub and Artifact](/docs/security/detective-security-hub-artifact)) - **"Download AWS compliance reports (SOC, PCI, ISO)", "accept the HIPAA BAA"** → AWS Artifact. ([Detective, Security Hub and Artifact](/docs/security/detective-security-hub-artifact)) ## Networking: Amazon VPC [#networking-amazon-vpc] - **"How many IPs in a /24?"** → 256 (minus the 5 AWS reserves in a subnet). ([CIDR and IP addressing](/docs/vpc/cidr-ip-addressing)) - **"Allow one IP in a security group"** → `/32`. **"Allow everyone"** → `0.0.0.0/0`. ([CIDR and IP addressing](/docs/vpc/cidr-ip-addressing)) - **"Private IP ranges"** → `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`. ([CIDR and IP addressing](/docs/vpc/cidr-ip-addressing)) - **"How many usable IPs in a /28 subnet?"** → 16 − 5 = **11**. ([VPC and subnets](/docs/vpc/vpc-and-subnets)) - **"Need N IPs"** → pick the smallest subnet where 2^(32−n) − 5 ≥ N. ([VPC and subnets](/docs/vpc/vpc-and-subnets)) - **"Plan to connect to on premises later"** → choose a VPC CIDR that doesn't overlap. ([VPC and subnets](/docs/vpc/vpc-and-subnets)) - **"Subnet spans two AZs"** → impossible; one subnet = one AZ. ([VPC and subnets](/docs/vpc/vpc-and-subnets)) - **"Instance in a public subnet can't reach the internet"** → check the route `0.0.0.0/0 → IGW`, a public IP, security groups and NACLs. ([Internet gateway and route tables](/docs/vpc/internet-gateway-route-tables)) - **"Make a subnet public"** → route table with `0.0.0.0/0` to an internet gateway. ([Internet gateway and route tables](/docs/vpc/internet-gateway-route-tables)) - **"SSH to instances in a private subnet"** → bastion host in a public subnet (or Session Manager / EIC Endpoint). ([Bastion hosts](/docs/vpc/bastion-hosts)) - **"Private instances need outbound internet (patches, APIs), no inbound"** → NAT gateway. ([NAT instance and NAT gateway](/docs/vpc/nat-instance-nat-gateway)) - **"Highly available NAT"** → one NAT gateway per AZ, each AZ's private subnets routing to their own (or a Regional NAT gateway). ([NAT instance and NAT gateway](/docs/vpc/nat-instance-nat-gateway)) - **"NAT instance not working"** → disable source/destination check, Elastic IP, route table, security groups. ([NAT instance and NAT gateway](/docs/vpc/nat-instance-nat-gateway)) - **"Least operational overhead"** → NAT gateway, not NAT instance. ([NAT instance and NAT gateway](/docs/vpc/nat-instance-nat-gateway)) - **"IPv6 outbound only"** → egress-only internet gateway, not NAT (see [IPv6](/docs/vpc/ipv6)). ([NAT instance and NAT gateway](/docs/vpc/nat-instance-nat-gateway)) - **"Block a specific IP address"** → NACL deny rule (security groups can't deny). ([NACLs vs security groups](/docs/vpc/nacl-vs-security-groups)) - **"Allowed inbound but the response never arrives"** → NACL outbound rules missing the ephemeral port range. ([NACLs vs security groups](/docs/vpc/nacl-vs-security-groups)) - **"Rule order"** → NACLs evaluate lowest number first; security groups evaluate all rules. ([NACLs vs security groups](/docs/vpc/nacl-vs-security-groups)) - **"Stateful vs stateless"** → security groups stateful, NACLs stateless. ([NACLs vs security groups](/docs/vpc/nacl-vs-security-groups)) - **"Troubleshoot why connections are rejected"**, **"which IPs talk to my instance"** → VPC Flow Logs. ([VPC Flow Logs and Traffic Mirroring](/docs/vpc/flow-logs-traffic-mirroring)) - **"Inbound ACCEPT but outbound REJECT"** → NACL (stateless) problem. ([VPC Flow Logs and Traffic Mirroring](/docs/vpc/flow-logs-traffic-mirroring)) - **"Analyse flow logs with SQL"** → S3 + Athena (or CloudWatch Logs Insights). ([VPC Flow Logs and Traffic Mirroring](/docs/vpc/flow-logs-traffic-mirroring)) - **"Inspect packet contents with an IDS appliance"** → Traffic Mirroring. ([VPC Flow Logs and Traffic Mirroring](/docs/vpc/flow-logs-traffic-mirroring)) - **"Protect the entire VPC", "filter outbound traffic by domain name", "intrusion prevention (IPS) for a VPC"** → AWS Network Firewall. ([AWS Network Firewall](/docs/vpc/network-firewall)) - **"Block malicious HTTP requests to an ALB"** → AWS WAF instead. ([AWS Network Firewall](/docs/vpc/network-firewall)) - **"Same firewall rules across many accounts"** → Firewall Manager with Network Firewall policies. ([AWS Network Firewall](/docs/vpc/network-firewall)) - **"Connect two VPCs privately"** → VPC peering (with route table updates). ([VPC peering](/docs/vpc/vpc-peering)) - **"VPC A peered with B and C; B can't reach C"** → peering isn't transitive; peer B and C, or use **[Transit Gateway](/docs/vpc/transit-gateway)**. ([VPC peering](/docs/vpc/vpc-peering)) - **"Peering fails to create"** → overlapping CIDRs. ([VPC peering](/docs/vpc/vpc-peering)) - **"Many VPCs (dozens or more)"** → Transit Gateway instead of a mesh of peerings. ([VPC peering](/docs/vpc/vpc-peering)) - **"Private access to S3 or DynamoDB from a VPC, cheapest"** → gateway endpoint. ([VPC endpoints and PrivateLink](/docs/vpc/vpc-endpoints-privatelink)) - **"Private access to SQS, SNS, KMS, Secrets Manager… from a private subnet"** → interface endpoint. ([VPC endpoints and PrivateLink](/docs/vpc/vpc-endpoints-privatelink)) - **"Access S3 privately from on premises over Direct Connect or VPN"** → S3 interface endpoint. ([VPC endpoints and PrivateLink](/docs/vpc/vpc-endpoints-privatelink)) - **"Expose a service to many VPCs, overlapping CIDRs, no peering"** → PrivateLink endpoint service with an NLB. ([VPC endpoints and PrivateLink](/docs/vpc/vpc-endpoints-privatelink)) - **"Endpoint created but traffic still fails"** → check DNS settings (private DNS) and route tables. ([VPC endpoints and PrivateLink](/docs/vpc/vpc-endpoints-privatelink)) - **"Connect many VPCs and on premises, transitive, hub-and-spoke"** → Transit Gateway. ([AWS Transit Gateway](/docs/vpc/transit-gateway)) - **"IP multicast"** → Transit Gateway. ([AWS Transit Gateway](/docs/vpc/transit-gateway)) - **"Increase VPN bandwidth beyond 1.25 Gbps"** → several Site-to-Site VPNs to a transit gateway with ECMP. ([AWS Transit Gateway](/docs/vpc/transit-gateway)) - **"Share one Direct Connect with many accounts' VPCs"** → transit VIF + DX gateway + transit gateway shared with RAM. ([AWS Transit Gateway](/docs/vpc/transit-gateway)) - **"Isolate some VPCs from others"** → transit gateway route tables. ([AWS Transit Gateway](/docs/vpc/transit-gateway)) - **"Connect the data center to AWS quickly, encrypted, over the internet"** → Site-to-Site VPN (VGW + CGW). ([Site-to-Site VPN and Client VPN](/docs/vpc/site-to-site-vpn)) - **"VPN up but no traffic"** → enable route propagation; check security groups (ICMP for ping). ([Site-to-Site VPN and Client VPN](/docs/vpc/site-to-site-vpn)) - **"Customer gateway behind NAT"** → use the NAT device's public IP with NAT-T. ([Site-to-Site VPN and Client VPN](/docs/vpc/site-to-site-vpn)) - **"Connect many branch offices to each other cheaply"** → VPN CloudHub. ([Site-to-Site VPN and Client VPN](/docs/vpc/site-to-site-vpn)) - **"Remote employees need secure access to the VPC"** → AWS Client VPN. ([Site-to-Site VPN and Client VPN](/docs/vpc/site-to-site-vpn)) - **"Dedicated, private, consistent network performance to AWS", "large data, low latency"** → Direct Connect. ([AWS Direct Connect](/docs/vpc/direct-connect)) - **"Need connectivity next week"** → Site-to-Site VPN (Direct Connect takes over a month). ([AWS Direct Connect](/docs/vpc/direct-connect)) - **"Encrypt traffic over Direct Connect"** → VPN over Direct Connect (IPsec), or MACsec. ([AWS Direct Connect](/docs/vpc/direct-connect)) - **"Direct Connect to VPCs in several Regions"** → Direct Connect gateway. ([AWS Direct Connect](/docs/vpc/direct-connect)) - **"Cheapest backup for Direct Connect"** → Site-to-Site VPN. ([AWS Direct Connect](/docs/vpc/direct-connect)) - **"Maximum resiliency"** → separate connections on separate devices at more than one location. ([AWS Direct Connect](/docs/vpc/direct-connect)) - **"Less than 1 Gbps, from a partner"** → hosted connection. ([AWS Direct Connect](/docs/vpc/direct-connect)) - **"Can't launch instances, subnet has IPv6"** → the subnet ran out of **IPv4** addresses; add an IPv4 CIDR. ([IPv6 in a VPC](/docs/vpc/ipv6)) - **"Private instances need outbound-only IPv6"** → egress-only internet gateway. ([IPv6 in a VPC](/docs/vpc/ipv6)) - **"Outbound-only IPv4"** → NAT gateway. ([IPv6 in a VPC](/docs/vpc/ipv6)) - **"Reduce data transfer cost between instances"** → same AZ, private IPs. ([Networking costs](/docs/vpc/networking-costs)) - **"Reduce cost of private instances accessing S3 or DynamoDB"** → gateway VPC endpoint instead of NAT gateway. ([Networking costs](/docs/vpc/networking-costs)) - **"Reduce S3 egress cost for global users"** → CloudFront in front of S3. ([Networking costs](/docs/vpc/networking-costs)) - **"Reduce egress from AWS to on premises"** → process data in AWS and send only results; Direct Connect. ([Networking costs](/docs/vpc/networking-costs)) ## Migration & Transfer [#migration--transfer] - **"Lift and shift", "least effort", "as is"** → rehost (MGN). ([Migration & Transfer](/docs/migration)) - **"Move to a managed database during migration"** → replatform (RDS, Aurora). ([Migration & Transfer](/docs/migration)) - **"Replace with SaaS"** → repurchase. **"Rebuild as serverless"** → refactor. ([Migration & Transfer](/docs/migration)) - **"Petabytes", "limited bandwidth", "would take weeks over the network"** → Snowball Edge. ([AWS Snowball Edge](/docs/migration/snow-family)) - **"Compute in a remote location with no internet"** → Snowball Edge Compute Optimized (today: Outposts). ([AWS Snowball Edge](/docs/migration/snow-family)) - **"Snowball into Glacier"** → import into S3, then a lifecycle rule to Glacier. ([AWS Snowball Edge](/docs/migration/snow-family)) - **"On-premises access to S3 over NFS or SMB", "local cache"** → S3 File Gateway. ([AWS Storage Gateway](/docs/migration/storage-gateway)) - **"iSCSI block storage backed by S3"** → Volume Gateway; **"low latency for recent data"** → cached volumes; **"whole dataset on premises, backed up to S3"** → stored volumes. ([AWS Storage Gateway](/docs/migration/storage-gateway)) - **"Replace physical tapes, keep the backup software"** → Tape Gateway. ([AWS Storage Gateway](/docs/migration/storage-gateway)) - **"No on-premises virtualization to run the gateway"** → hardware appliance. ([AWS Storage Gateway](/docs/migration/storage-gateway)) - **"Partners send files over SFTP / FTPS / FTP into S3 or EFS, no servers to manage"** → Transfer Family. ([AWS Transfer Family](/docs/migration/transfer-family)) - **"Keep existing FTP clients and scripts"** → Transfer Family. ([AWS Transfer Family](/docs/migration/transfer-family)) - **"Move or sync files online from NFS/SMB to S3, EFS or FSx"** → DataSync (with an agent). ([AWS DataSync](/docs/migration/datasync)) - **"Copy between EFS, FSx and S3", "keep metadata and permissions"** → DataSync. ([AWS DataSync](/docs/migration/datasync)) - **"Scheduled transfers"** → DataSync tasks. **"Ongoing on-premises access to S3 files"** → Storage Gateway instead. ([AWS DataSync](/docs/migration/datasync)) - **"Hundreds of TB, slow link, needed in weeks"** → Snowball (offline). ([Transferring large amounts of data](/docs/migration/large-data-transfer)) - **"Quick setup, small amounts"** → internet / Site-to-Site VPN. ([Transferring large amounts of data](/docs/migration/large-data-transfer)) - **"Ongoing, consistent, high bandwidth"** → Direct Connect (plus DataSync or DMS). ([Transferring large amounts of data](/docs/migration/large-data-transfer)) - **"Migrate a database with minimal downtime, source stays live"** → DMS (full load + CDC). ([DMS and schema conversion](/docs/migration/dms-sct)) - **"Different engines (Oracle → Aurora, SQL Server → MySQL)"** → schema conversion (SCT or DMS Schema Conversion) + DMS. ([DMS and schema conversion](/docs/migration/dms-sct)) - **"Same engine (PostgreSQL → RDS PostgreSQL)"** → DMS (or native tools) without SCT. ([DMS and schema conversion](/docs/migration/dms-sct)) - **"Teradata or Oracle data warehouse to Redshift"** → SCT + DMS. ([DMS and schema conversion](/docs/migration/dms-sct)) - **"RDS MySQL to Aurora"** → snapshot restore, or Aurora read replica then promote. ([DMS and schema conversion](/docs/migration/dms-sct)) - **"Stream database changes to Kinesis"** → DMS with Kinesis Data Streams as the target. ([DMS and schema conversion](/docs/migration/dms-sct)) - **"Plan a migration: inventory, utilization, dependencies of on-premises servers"** → Application Discovery Service (agentless for VMware inventory; agent for processes and network connections). ([Application Discovery Service and MGN](/docs/migration/application-discovery-mgn)) - **"Lift and shift servers to EC2 with minimal downtime"** → Application Migration Service (MGN). ([Application Discovery Service and MGN](/docs/migration/application-discovery-mgn)) - **"CloudEndure Migration" or "Server Migration Service" in an old question** → MGN. ([Application Discovery Service and MGN](/docs/migration/application-discovery-mgn)) - **"Track migration progress in one place"** → Migration Hub (closed to new customers). ([Application Discovery Service and MGN](/docs/migration/application-discovery-mgn)) ## Disaster Recovery & Backup [#disaster-recovery--backup] - **"How much data can we afford to lose?"** → RPO. **"How long can we be down?"** → RTO. ([Disaster Recovery & Backup](/docs/dr)) - **"Lowest cost, RPO/RTO of hours is fine"** → backup and restore. ([Disaster recovery strategies](/docs/dr/dr-strategies)) - **"Database must stay in sync, servers can start on failover, tens of minutes"** → pilot light. ([Disaster recovery strategies](/docs/dr/dr-strategies)) - **"Scaled-down full copy always running, minutes"** → warm standby. ([Disaster recovery strategies](/docs/dr/dr-strategies)) - **"Near-zero downtime, cost no object"** → multi-site active/active. ([Disaster recovery strategies](/docs/dr/dr-strategies)) - **"Multi-Region DR for a relational database with RPO of about a second"** → Aurora Global Database. ([Disaster recovery strategies](/docs/dr/dr-strategies)) - **"Recover on-premises servers into AWS within minutes, low RPO (seconds)"** → Elastic Disaster Recovery. ([AWS Elastic Disaster Recovery](/docs/dr/elastic-disaster-recovery)) - **"CloudEndure Disaster Recovery"** → Elastic Disaster Recovery. ([AWS Elastic Disaster Recovery](/docs/dr/elastic-disaster-recovery)) - **"Recover to a point in time before a ransomware attack"** → DRS point-in-time recovery. ([AWS Elastic Disaster Recovery](/docs/dr/elastic-disaster-recovery)) - **"Centralize and automate backups across services and accounts"** → AWS Backup (+ Organizations backup policies). ([AWS Backup](/docs/dr/aws-backup)) - **"Copy backups to another Region or account automatically"** → AWS Backup copy rules. ([AWS Backup](/docs/dr/aws-backup)) - **"Backups must be immutable, protected even from root / ransomware"** → Backup Vault Lock (compliance mode). ([AWS Backup](/docs/dr/aws-backup)) - **"Back up resources by tag"** → tag-based backup plans. ([AWS Backup](/docs/dr/aws-backup)) ## Cost Management [#cost-management] - **"Alert when spend goes over a threshold"** → AWS Budgets. **"Unexpected, unusual spend without setting thresholds"** → Cost Anomaly Detection. ([Cost Management](/docs/cost)) - **"Visualize and forecast costs", "Savings Plans recommendations"** → Cost Explorer. ([Cost Management](/docs/cost)) - **"Most detailed billing data, query with Athena"** → Cost and Usage Report. ([Cost Management](/docs/cost)) - **"Costs per team or project"** → cost allocation tags (activated in Billing). ([Cost Management](/docs/cost)) - **"One bill and shared discounts across accounts"** → consolidated billing. ([Cost Management](/docs/cost)) - **"Visualize costs, group by service or tag, forecast"** → Cost Explorer. ([Cost Explorer and Cost Anomaly Detection](/docs/cost/cost-explorer-anomaly)) - **"Recommend a Savings Plan or Reserved Instances"** → Cost Explorer recommendations. ([Cost Explorer and Cost Anomaly Detection](/docs/cost/cost-explorer-anomaly)) - **"Detect unusual spending automatically, no thresholds"** → Cost Anomaly Detection. ([Cost Explorer and Cost Anomaly Detection](/docs/cost/cost-explorer-anomaly)) - **"Alert when cost exceeds or is forecast to exceed X"** → AWS Budgets. ([Budgets, Cost and Usage Report and cost allocation tags](/docs/cost/budgets-cur-tags)) - **"Automatically stop instances or block launches when the budget is exceeded"** → budget actions. ([Budgets, Cost and Usage Report and cost allocation tags](/docs/cost/budgets-cur-tags)) - **"Track if Reserved Instances or Savings Plans are being used"** → RI/SP utilization budgets. ([Budgets, Cost and Usage Report and cost allocation tags](/docs/cost/budgets-cur-tags)) - **"Most granular billing data, hourly, per resource, query with Athena"** → Cost and Usage Report. ([Budgets, Cost and Usage Report and cost allocation tags](/docs/cost/budgets-cur-tags)) - **"Costs per department or project"** → cost allocation tags (activated) or cost categories. ([Budgets, Cost and Usage Report and cost allocation tags](/docs/cost/budgets-cur-tags)) - **"Stop development instances outside business hours automatically, lowest effort"** → Instance Scheduler on AWS. ([Instance Scheduler on AWS](/docs/cost/instance-scheduler)) - **"Start and stop RDS on a schedule"** → Instance Scheduler (or EventBridge + Lambda yourself). ([Instance Scheduler on AWS](/docs/cost/instance-scheduler)) ## Architecture Patterns [#architecture-patterns] - **"Highly available web tier on EC2"** → ALB + Auto Scaling group across at least two AZs. ([Stateless web app: WhatIsTheTime.com](/docs/architecture/stateless-web-app)) - **"Point a domain name at a load balancer"** → Route 53 **alias** record, never an A record with IPs. ([Stateless web app: WhatIsTheTime.com](/docs/architecture/stateless-web-app)) - **"Instances should only accept traffic from the load balancer"** → instance security group allows the ALB's security group as the source. ([Stateless web app: WhatIsTheTime.com](/docs/architecture/stateless-web-app)) - **"Steady minimum capacity, cheapest"** → Reserved Instances or Savings Plans for the minimum, On-Demand or Spot above it. ([Stateless web app: WhatIsTheTime.com](/docs/architecture/stateless-web-app)) - **"Users lose their session (cart, login) when instances scale in"** → store sessions in **ElastiCache** or **DynamoDB**, not on the instance. ([Stateful web app: MyClothes.com](/docs/architecture/stateful-web-app)) - **"Stateless web tier"** → session data outside the instances (cache, database, or signed cookies). ([Stateful web app: MyClothes.com](/docs/architecture/stateful-web-app)) - **"Read-heavy RDS"** → read replicas, or ElastiCache in front. ([Stateful web app: MyClothes.com](/docs/architecture/stateful-web-app)) - **"Database tier reachable only from the app tier"** → database security group allows the app tier's security group. ([Stateful web app: MyClothes.com](/docs/architecture/stateful-web-app)) - **"Several EC2 instances must share files (uploads, content)"** → **EFS** (Linux) or **FSx for Windows File Server** (Windows). ([WordPress and fast launches](/docs/architecture/wordpress)) - **"MySQL, Multi-AZ, read scaling, less management"** → **Aurora MySQL**. ([WordPress and fast launches](/docs/architecture/wordpress)) - **"Instances take too long to boot because of software installs"** → **golden AMI**; use user data only for the dynamic part. ([WordPress and fast launches](/docs/architecture/wordpress)) - **"Database ready with data at launch"** → restore from an **RDS snapshot**. ([WordPress and fast launches](/docs/architecture/wordpress)) - **"Mobile app users upload to their own folder in S3"** → Cognito **identity pool** + IAM policy with `${cognito-identity.amazonaws.com:sub}`. ([Serverless mobile app: MyTodoList](/docs/architecture/serverless-mobile-app)) - **"Sign-in for a mobile or web app, serverless"** → Cognito **user pools**. ([Serverless mobile app: MyTodoList](/docs/architecture/serverless-mobile-app)) - **"Read-heavy DynamoDB, microsecond latency"** → **DAX**. ([Serverless mobile app: MyTodoList](/docs/architecture/serverless-mobile-app)) - **"Same responses requested again and again through API Gateway"** → **API Gateway caching**. ([Serverless mobile app: MyTodoList](/docs/architecture/serverless-mobile-app)) - **"Static website, global, secure, S3 not public"** → CloudFront + S3 with **OAC** and a bucket policy for the distribution. ([Serverless website: MyBlog.com](/docs/architecture/serverless-website)) - **"Send an email when an item is added to DynamoDB"** → DynamoDB Streams → Lambda → SES. ([Serverless website: MyBlog.com](/docs/architecture/serverless-website)) - **"Process images when they're uploaded"** → S3 event notification → Lambda. ([Serverless website: MyBlog.com](/docs/architecture/serverless-website)) - **"Low-latency reads worldwide, NoSQL"** → DynamoDB global tables. ([Serverless website: MyBlog.com](/docs/architecture/serverless-website)) - **"Decouple microservices, one shouldn't wait for another"** → SQS, SNS, Kinesis or EventBridge between them. ([Microservices and offloading downloads](/docs/architecture/microservices)) - **"Microservices, pay only when used, little to manage"** → API Gateway + Lambda (or Fargate). ([Microservices and offloading downloads](/docs/architecture/microservices)) - **"Large static downloads overload EC2, can't change the app"** → CloudFront in front of the existing origin. ([Microservices and offloading downloads](/docs/architecture/microservices)) - **"Send the same message to several services reliably"** → SNS topic with SQS subscriptions (**fan-out**). ([Event processing](/docs/architecture/event-processing)) - **"Order matters and messages must not be lost when Lambda fails"** → SQS FIFO + Lambda, with a DLQ. ([Event processing](/docs/architecture/event-processing)) - **"React to object uploads"** → S3 event notifications; **"advanced filtering, many targets, replay"** → S3 → EventBridge. ([Event processing](/docs/architecture/event-processing)) - **"Alert when someone calls a specific API"** → CloudTrail → EventBridge rule → SNS. ([Event processing](/docs/architecture/event-processing)) - **"Expose Kinesis (or SQS, DynamoDB) to clients over HTTPS without Lambda"** → API Gateway AWS service integration. ([Event processing](/docs/architecture/event-processing)) - **"Static content, global users, reduce load on the origin"** → CloudFront. ([Caching strategies](/docs/architecture/caching-strategies)) - **"Same API responses requested repeatedly"** → API Gateway caching (or CloudFront in front of the API). ([Caching strategies](/docs/architecture/caching-strategies)) - **"Database read load, sub-millisecond reads"** → ElastiCache; **"DynamoDB, microseconds, no code change"** → DAX. ([Caching strategies](/docs/architecture/caching-strategies)) - **"Users see old data after an update"** → shorter TTLs, CloudFront invalidations, or write-through caching. ([Caching strategies](/docs/architecture/caching-strategies)) - **"Block a specific IP address at the subnet level"** → **NACL deny rule**. ([Blocking an IP address](/docs/architecture/blocking-ip-addresses)) - **"Security groups can deny an IP"** → false: SGs only allow. ([Blocking an IP address](/docs/architecture/blocking-ip-addresses)) - **"Block IPs with CloudFront in front"** → **WAF on CloudFront** (IP set); NACLs only see CloudFront IPs. ([Blocking an IP address](/docs/architecture/blocking-ip-addresses)) - **"Block a country"** → CloudFront geo restriction or a WAF geo match rule. ([Blocking an IP address](/docs/architecture/blocking-ip-addresses)) - **"Tightly coupled HPC, MPI, lowest latency between nodes"** → **EFA** + **cluster placement group**. ([High performance computing (HPC)](/docs/architecture/hpc)) - **"High-performance file system for HPC, data in S3"** → **FSx for Lustre**. ([High performance computing (HPC)](/docs/architecture/hpc)) - **"Enhanced networking, up to 100 Gbps"** → **ENA**. ([High performance computing (HPC)](/docs/architecture/hpc)) - **"Run batch jobs across many instances"** → **AWS Batch** (multi-node parallel jobs). ([High performance computing (HPC)](/docs/architecture/hpc)) - **"Deploy and manage an HPC cluster with a scheduler"** → **ParallelCluster** (or AWS PCS for a managed Slurm). ([High performance computing (HPC)](/docs/architecture/hpc)) - **"Single instance, must survive an AZ failure, fixed public IP"** → ASG min/max/desired 1 across 2+ AZs + user data that attaches the Elastic IP (with an instance role). ([Highly available EC2 instance](/docs/architecture/highly-available-ec2)) - **"Automatically recover an instance after a hardware failure, same IP"** → EC2 automatic recovery (CloudWatch `StatusCheckFailed_System`). ([Highly available EC2 instance](/docs/architecture/highly-available-ec2)) - **"Run custom actions when an ASG launches or terminates an instance"** → **lifecycle hooks**. ([Highly available EC2 instance](/docs/architecture/highly-available-ec2)) - **"Review an architecture against AWS best practices"** → **Well-Architected Tool** (free). ([Well-Architected Framework and Trusted Advisor](/docs/architecture/well-architected)) - **"Name the pillars"** → operational excellence, security, reliability, performance efficiency, cost optimization, sustainability. ([Well-Architected Framework and Trusted Advisor](/docs/architecture/well-architected)) - **"Automatically check for idle resources, open security groups and service limits"** → **Trusted Advisor**. ([Well-Architected Framework and Trusted Advisor](/docs/architecture/well-architected)) - **"Get notified when a service quota is close to its limit"** → Trusted Advisor service limits checks or **Service Quotas** CloudWatch alarms. ([Well-Architected Framework and Trusted Advisor](/docs/architecture/well-architected)) - **"Avoid configuration drift, replace instead of patching"** → immutable infrastructure: new AMI + new instances. ([Immutable infrastructure](/docs/architecture/immutable-infrastructure)) - **"Automate building and patching AMIs"** → **EC2 Image Builder**. ([Immutable infrastructure](/docs/architecture/immutable-infrastructure)) - **"Deploy with near-zero downtime and instant rollback"** → **blue/green** (CodeDeploy, Elastic Beanstalk, Route 53 weighted). ([Immutable infrastructure](/docs/architecture/immutable-infrastructure)) - **"Test a new version on a small share of traffic first"** → **canary** deployment. ([Immutable infrastructure](/docs/architecture/immutable-infrastructure)) - **"Find resources changed outside CloudFormation"** → **drift detection**. ([Immutable infrastructure](/docs/architecture/immutable-infrastructure)) # Console, CLI and SDK (/docs/foundations/console-cli-sdk) ## What it is [#what-it-is] There are three ways to work with AWS: - **The [AWS Management Console](/docs/glossary#term-aws-management-console):** the website at `console.aws.amazon.com`. You sign in with a password, plus MFA. - **The [AWS CLI](/docs/glossary#term-aws-cli) (Command Line Interface):** a program you run in a terminal. It signs in with short-term credentials from a sign-in, or with access keys. - **The [AWS SDKs](/docs/glossary#term-aws-sdk) (Software Development Kits):** libraries you call from your own code. They use short-term credentials, an IAM role, or access keys. All three do the same thing underneath: they send requests to AWS's public service APIs over HTTPS. Whatever you can click in the console, you can also do with a CLI command or a line of code. They exist because people work differently. The console is easiest for learning and one-off tasks. The CLI is faster for repeated tasks and scripts. The SDKs let applications use AWS directly, for example to save an upload to S3. ## How it works [#how-it-works]
![The Console, CLI and SDK all send HTTPS API calls that IAM checks before a service acts](/diagrams/foundations-access-paths.light.svg) ![The Console, CLI and SDK all send HTTPS API calls that IAM checks before a service acts](/diagrams/foundations-access-paths.dark.svg)
Three ways in, one set of APIs.
On the left are the three ways in, each with how it signs in: the Management Console with a password and MFA, the AWS CLI with access keys or single sign-on, and the AWS SDK with access keys or an IAM role. All three send HTTPS requests to the same public service APIs inside AWS. Each request is checked by IAM first: who is calling, and are they allowed to do this action? Only then does the service (EC2, S3, DynamoDB and so on) carry out the request. Every action is one API call. Clicking **Launch instance** in the console, running `aws ec2 run-instances` and calling `ec2.run_instances()` in Python all send the same `RunInstances` request. ## The AWS Management Console [#the-aws-management-console] The console is a website where you see and manage your resources with forms and buttons. - You sign in with an email (root user) or a user name and password (IAM user), and you should always add **MFA**: a second factor such as a code from an authenticator app or a security key. MFA is covered in the Identity & Access group. - The **Region menu** (top right) sets which Region you're working in. Global services such as IAM show **Global** there. - The **search bar** (top) finds any service by name. - Each service has its own console page, with a dashboard and links to its resources. The console is the best way to learn a service. For anything you'll do more than twice, the CLI or code is faster and less error-prone. ## The AWS CLI [#the-aws-cli] The AWS CLI lets you control AWS by typing commands in a terminal. It's open source ([github.com/aws/aws-cli](https://github.com/aws/aws-cli)) and calls the same public APIs as the console. Commands follow one pattern: `aws [options]`. ```bash # Copy a file to an S3 bucket, then list the bucket aws s3 cp myfile.txt s3://my-example-bucket/myfile.txt aws s3 ls s3://my-example-bucket # Show which identity you're signed in as aws sts get-caller-identity ``` The current major version is **AWS CLI v2**. AWS publishes official installers for macOS, Linux and Windows. Copies from other package managers are unofficial. ### Signing the CLI in [#signing-the-cli-in] The CLI needs credentials before it can call anything. AWS lists several ways, from most to least recommended: 1. **Console sign-in: `aws login`.** Opens a browser, you sign in as you would to the console, and the CLI gets short-term credentials that refresh for up to 12 hours. Best for your own laptop. Needs CLI 2.32.0 or later. 2. **IAM Identity Center (single sign-on): `aws configure sso`.** Short-term credentials through your organisation's sign-in. AWS's best practice for companies. 3. **An IAM role on an EC2 instance.** Nothing to configure: the CLI finds the role's short-term credentials by itself, and AWS rotates them. 4. **An IAM user's access keys: `aws configure`.** Long-term credentials that work until someone deletes them. Use them only when nothing else works. `aws configure` asks for four things: an **access key ID**, a **secret access key**, a **default Region** and a **default output format** (`json`, `text` or `table`). It saves them in two files in `~/.aws/`: `credentials` and `config`. **Profiles** let you keep several sets of credentials side by side, for example one per account. Add `--profile ` to a command to use one. Without it, the CLI uses the profile called `default`. ### Access keys [#access-keys] An [access key](/docs/glossary#term-access-key) is a pair of values that lets the CLI or SDK act as an IAM user: - **Access key ID**, like a user name: `AKIAIOSFODNN7EXAMPLE` (an example from the AWS docs, not a real key). - **Secret access key**, like a password: shown only once, when you create it. Access keys are long-term: they work until someone deletes or deactivates them. Anyone who gets a copy can act as you. Treat them like a password: never share them, never put them in code, and never commit them to git. Create and manage them in the IAM console; the Identity & Access group covers this in depth. The slides show `aws configure` with access keys as the normal way to set up the CLI. AWS now recommends short-term credentials instead: `aws login` (added in CLI 2.32.0) for your own machine, or IAM Identity Center for organisations. It marks long-term IAM user access keys as *not recommended*. ## The AWS SDKs [#the-aws-sdks] An SDK is a set of libraries that call AWS APIs from inside your application. AWS provides SDKs for JavaScript/Node.js, Python (`boto3`), Java, .NET, Go, PHP, Ruby, C++, Rust, Kotlin and Swift, plus mobile and IoT device SDKs. ```python title="list_buckets.py" import boto3 s3 = boto3.client("s3") for bucket in s3.list_buckets()["Buckets"]: print(bucket["Name"]) ``` The SDKs look for credentials in the same places as the CLI. On AWS (EC2, Lambda, ECS), give the code an **IAM role** and the SDK picks up short-term credentials by itself. The SDKs also retry failed calls for you, which matters for [throttling](/docs/foundations/service-quotas#throttling). Fun fact: the AWS CLI is built on the AWS SDK for Python. ## AWS CloudShell [#aws-cloudshell] **AWS CloudShell** is a terminal that runs in your browser, opened from the console's top bar. It's useful for labs because there's nothing to install. - It comes with the AWS CLI, Python, Node.js and common tools already installed. - It's **already signed in** as you, using your console credentials: no access keys needed. - It has **no extra charge**. You pay only for the resources your commands create. - Each Region gives you **1 GB of persistent storage** in your home folder. Files elsewhere disappear when the session ends. CloudShell is on the exam's out-of-scope list, so it won't be tested. It's simply the easiest place to run the CLI in these labs. ## Exam tips [#exam-tips] - **"An application on EC2 needs to call S3"** → give the instance an **IAM role**. Never store access keys on the instance. - **"Developers need CLI access across many accounts"** → **IAM Identity Center** with `aws configure sso` (short-term credentials). - **"Access keys were committed to a public repository"** → deactivate and delete the keys straight away, then check CloudTrail for what they were used for. - **"Automate the same task repeatedly"** → CLI scripts or SDK code, or infrastructure as code (CloudFormation). - **"Who can use the console?"** → anyone with a user name and password (and MFA). The CLI and SDKs need credentials, not a password. "Store access keys on the EC2 instance" or "embed access keys in the application" is almost always a wrong answer. The right answer is an IAM role. ## Common traps [#common-traps] - **"Use the root user's access keys for the CLI."** The root user shouldn't have access keys at all. Use an IAM identity with least privilege. - **"Share one IAM user's keys among the team."** Each person needs their own identity, so actions can be traced and access removed one person at a time. - **"The CLI can do things the console can't, so it bypasses IAM."** Every call goes through the same APIs and the same IAM checks. - **"CloudShell costs money per hour."** CloudShell has no charge; only the resources you create are billed. ## Hands-on lab: use the CLI two ways [#hands-on-lab-use-the-cli-two-ways] **Goal:** run AWS CLI commands in CloudShell, then from your own computer with short-term credentials. These commands only read information. Nothing billable is created. **Before you start:** sign in to the console in **US East (N. Virginia)**. ### Part 1: CloudShell [#part-1-cloudshell] ### Open CloudShell [#open-cloudshell] Choose the CloudShell icon in the console's top bar and wait for the prompt. ### Check who you are [#check-who-you-are] ```bash aws sts get-caller-identity ``` The output shows three fields: `UserId`, `Account` (your 12-digit account ID) and `Arn` (the full name of your identity, for example `arn:aws:iam::123456789012:user/alex`). ### Try a few read-only commands [#try-a-few-read-only-commands] ```bash aws ec2 describe-regions --output table aws s3 ls aws iam list-users --query "Users[].UserName" ``` `aws s3 ls` prints nothing if you have no buckets yet. That's fine. ### Find help [#find-help] ```bash aws ec2 describe-instances help ``` Press `q` to leave the help page. Every command has one. ### Part 2: your own computer [#part-2-your-own-computer] ### Install the AWS CLI v2 [#install-the-aws-cli-v2] Follow [Installing the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) for your system, then check the version: ```bash aws --version ``` You need version 2.32.0 or later for `aws login`. ### Sign in with your console credentials [#sign-in-with-your-console-credentials] ```bash aws login ``` A browser window opens. Sign in as you would to the console and approve the request. The CLI stores short-term credentials and refreshes them for up to 12 hours. If you're signing in as an IAM user, that user needs the AWS managed policy `SignInLocalDevelopmentAccess`. The root user doesn't, but avoid using root for daily work. ### Confirm it works [#confirm-it-works] ```bash aws sts get-caller-identity aws configure set region us-east-1 aws ec2 describe-availability-zones --output table ``` ### Sign out [#sign-out] ```bash aws logout ``` This deletes the cached short-term credentials from your computer. **Expected result:** the same identity and results in CloudShell and on your computer, without ever creating an access key. **Clean up:** run `aws logout` (done above) and close CloudShell. No resources were created. ## AWS documentation [#aws-documentation] - [What is the AWS Command Line Interface?](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) - [Installing or updating the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) - [Setting up the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-quickstart.html) - [Signing in to the AWS CLI with console credentials (`aws login`)](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sign-in.html) - [What is AWS CloudShell?](https://docs.aws.amazon.com/cloudshell/latest/userguide/welcome.html) - [Tools to build on AWS](https://aws.amazon.com/developer/tools/) # Global infrastructure (/docs/foundations/global-infrastructure) ## What it is [#what-it-is] AWS's global infrastructure is the physical side of the cloud: buildings full of servers, spread around the world and joined by AWS's own network. It's organised in layers: - A [Region](/docs/glossary#term-region) is a geographic area, such as Northern Virginia or Sydney. - Each Region has several [Availability Zones](/docs/glossary#term-availability-zone) (AZs). - Each AZ is one or more data centers. - Outside the Regions, [edge locations](/docs/glossary#term-edge-location), [Local Zones](/docs/glossary#term-local-zone) and [Wavelength Zones](/docs/glossary#term-wavelength-zone) bring some services closer to users. It exists for two reasons. Spreading copies of an application across separate buildings keeps it running when one building fails. And placing it near users makes it faster for them. ## How it works [#how-it-works]
![AWS global infrastructure: a Region with three Availability Zones, plus Local Zones, Wavelength Zones and edge locations](/diagrams/foundations-global-infrastructure.light.svg) ![AWS global infrastructure: a Region with three Availability Zones, plus Local Zones, Wavelength Zones and edge locations](/diagrams/foundations-global-infrastructure.dark.svg)
A Region, its Availability Zones, and the locations outside it.
The Region `us-east-1` (Northern Virginia) contains three Availability Zones: `us-east-1a`, `us-east-1b` and `us-east-1c`. Each AZ is one or more data centers with its own power and cooling. The AZs are joined to each other by fast private fibre, and all of them sit within 100 km of each other. Below the Region are three kinds of location outside it: - a **Local Zone**: compute in a large city, linked to a parent Region; - a **Wavelength Zone**: compute inside a mobile carrier's 5G network; - **edge locations**: sites used by CloudFront and Route 53 to serve users nearby. ## Regions [#regions] A Region is a separate geographic area that contains a cluster of data centers. Each Region has a code and a name, for example: - `us-east-1`: US East (N. Virginia) - `eu-west-3`: Europe (Paris) - `ap-southeast-1`: Asia Pacific (Singapore) - `ap-southeast-2`: Asia Pacific (Sydney) Key facts: - **Most services are Regional.** An EC2 instance, an RDS database or an SQS queue lives in one Region. Choose the Region in the top-right corner of the console before you create anything, or you'll create it in the wrong place. - **Regions are isolated from each other.** A problem in one Region doesn't spread to another. Your data stays in the Region you put it in unless you copy it out yourself. - **Some Regions are opt-in.** Regions launched after 20 March 2019 (for example Cape Town, Hong Kong, Milan, Jakarta) are turned off for new accounts. An administrator enables them in the account settings before anyone can use them. The 17 older Regions are on by default. - **Special partitions:** AWS GovCloud (US) and the China Regions need separate accounts and can't be reached from a normal account. As of November 2026, AWS lists 39 geographic Regions with 124 Availability Zones, and has announced more (including Saudi Arabia and Chile). The numbers grow every year: check the [global infrastructure page](https://aws.amazon.com/about-aws/global-infrastructure/) for today's count. ### How to choose a Region [#how-to-choose-a-region]
![Choosing a Region: compliance, then latency, then services, then pricing](/diagrams/foundations-choosing-region.light.svg) ![Choosing a Region: compliance, then latency, then services, then pricing](/diagrams/foundations-choosing-region.dark.svg)
The four factors, in the order you check them.
When a company launches a new application, four questions decide the Region, in this order: 1. **Compliance: must the data stay in a country?** Laws and contracts can require data to stay in a country or region, and data never leaves a Region unless you move it. A French hospital's patient data must stay in the EU, so it uses `eu-west-3` (Paris). This is a hard rule: if the data can't leave, the other three factors don't matter. 2. **Latency: where are most of the users?** The closer the Region, the faster the app feels. An app for Australian users runs in `ap-southeast-2` (Sydney). 3. **Services: does the Region have what we need?** New services and features don't reach every Region at once; they often launch in `us-east-1` first. The [Regional product services list](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) shows what each Region offers. 4. **Pricing: what does it cost there?** Prices vary by Region and are listed on each service's pricing page. The same instance costs more in São Paulo than in Ohio. ## Availability Zones [#availability-zones] An Availability Zone is one or more separate data centers inside a Region, with redundant power, networking and connectivity. - **Every Region has at least three AZs.** Most have three; a few large Regions have more (`us-east-1` has six). - **AZ names** are the Region code plus a letter: `ap-southeast-2a`, `ap-southeast-2b`, `ap-southeast-2c`. - **AZs are isolated from each other.** Each has its own power, cooling and physical security, many kilometres from the others, so a fire, flood or power cut in one doesn't take down the rest. - **AZs are close enough to work together.** All AZs in a Region are within 100 km (60 miles) of each other and joined by high-bandwidth, low-latency private fibre. It's fast enough to copy data between AZs *synchronously*, meaning every write lands in two AZs before it's confirmed. [RDS Multi-AZ](/docs/databases/rds-read-replicas-multi-az#multi-az) relies on this. ### AZ names and AZ IDs [#az-names-and-az-ids] Each AZ also has an [AZ ID](/docs/glossary#term-az-id), such as `use1-az1`. The AZ ID always points to the same physical location, in every account. The AZ *name* (`us-east-1a`) might not. In older accounts, AWS mapped names to physical AZs at random per account, to spread customers evenly: your `us-east-1a` and another account's `us-east-1a` could be different buildings. Accounts created since November 2025 get the same mapping as everyone else. This matters when two accounts must use the *same* physical AZ, for example to keep traffic between them inside one AZ. Compare AZ IDs, not names. The slides say a Region has "usually 3, min 3, max 6" AZs. AWS now states only the minimum: every Region has at least three AZs. The mapping of AZ names for new accounts also changed in November 2025, as described above. ## Edge locations (Points of Presence) [#edge-locations-points-of-presence] Edge locations are small sites in many more cities than there are Regions. They don't run your servers. They run a few global services that work best close to users: - **Amazon CloudFront** caches copies of your files there, so users download them from nearby. - **Amazon Route 53** answers DNS queries from there. - **AWS Global Accelerator**, **AWS WAF** and **AWS Shield** also work at the edge. CloudFront calls these sites **Points of Presence (PoPs)**. Between the PoPs and your servers sit **Regional edge caches**: larger caches that hold files that aren't popular enough to stay at every PoP. Today AWS has **750+ PoPs in 100+ cities across 50+ countries, and 15 Regional edge caches**. The slides give 400+ PoPs in 90+ cities across 40+ countries, with 10+ Regional edge caches. The figures above are from the CloudFront features page in November 2026. You'll learn how caching at the edge works in the [CloudFront](/docs/edge/cloudfront) notes, in the [DNS & Content Delivery](/docs/edge) group. ## Local Zones and Wavelength Zones [#local-zones-and-wavelength-zones] These bring a small part of a Region closer to users who need very low latency. They're on the exam list but not in the course slides. **Local Zones** place compute, storage, database and some other services in or near large cities and industry centres, far from the nearest Region. Each Local Zone is linked to a parent Region: you extend a VPC from the parent Region by adding a subnet in the Local Zone. You opt in to each Local Zone before you use it. - *Uses:* real-time gaming, live video streaming, AR/VR, virtual desktops for media studios, and data that must stay in a city or state. - *Example:* a film studio in Los Angeles runs editing workstations in the Los Angeles Local Zone, so artists get a smooth, single-digit-millisecond connection. **Wavelength Zones** put AWS compute and storage inside a telecom carrier's 5G network. Traffic from phones on that network reaches your app without leaving the carrier's network. A **carrier gateway** connects the Wavelength subnet to the carrier network. - *Uses:* apps that must respond to mobile devices in milliseconds: connected cars, live video analytics, cloud gaming on phones. **AWS Outposts** goes one step further: AWS installs its own hardware in *your* data center. It's covered in [Hybrid and edge compute](/docs/compute/hybrid-edge-compute#aws-outposts). ### Region, Local Zone, Wavelength Zone or edge location? [#region-local-zone-wavelength-zone-or-edge-location]
![What runs in a Region, a Local Zone, a Wavelength Zone and an edge location](/diagrams/foundations-edge-options.light.svg) ![What runs in a Region, a Local Zone, a Wavelength Zone and an edge location](/diagrams/foundations-edge-options.dark.svg)
Four kinds of location, from a Region to the edge.
Moving from left to right brings you closer to the user, but fewer services run there: - **A Region** runs every service. It's where your main workload lives. - **A Local Zone** runs selected services such as EC2, EBS and some databases, near a big city. Use it when users in that city need the lowest latency. - **A Wavelength Zone** runs EC2, EBS and a few others inside a 5G network. Use it for apps on mobile devices. - **An edge location** doesn't run your servers at all. It runs AWS's own caching (CloudFront) and DNS (Route 53) near users. ## Global vs Regional services [#global-vs-regional-services] Most AWS services are **Regional**: you pick a Region and the resource lives there. A few are **global**: you configure them once, and they work everywhere. In the console, global services show **Global** in the Region menu instead of a Region name. **Global services:** - IAM (users, roles, policies) - Amazon Route 53 (DNS) - Amazon CloudFront (content delivery network) - AWS WAF, when used with CloudFront **Regional services** (most of them), for example: - Amazon EC2 (IaaS) - AWS Elastic Beanstalk (PaaS) - AWS Lambda (FaaS) - Amazon Rekognition (SaaS) ## Real-world examples [#real-world-examples] - **A news website** runs its servers in `us-east-1`, spread across three AZs so it survives a data center failure. CloudFront serves its images and pages from edge locations, so readers in Tokyo don't wait for every file to cross the Pacific. - **A European bank** must keep customer data in the EU. It runs in `eu-central-1` (Frankfurt) and keeps a disaster-recovery copy in `eu-west-1` (Ireland), both inside the EU. - **A mobile game** runs its matchmaking in a Region, but its real-time game servers in Local Zones near big cities, so players get low ping. ## Exam tips [#exam-tips] - **"Data must not leave the country", "data residency"** → choose a Region in that country. Compliance beats latency and price. - **"Highly available", "survive a data center failure"** → spread across **multiple AZs** in one Region. - **"Survive the loss of a whole Region", "disaster recovery in another geography"** → **multiple Regions**. - **"Users worldwide", "reduce latency for static content"** → edge locations through **CloudFront**. - **"Single-digit millisecond latency for users in a specific city"** → **Local Zones**. - **"Ultra-low latency for mobile / 5G devices"** → **Wavelength Zones**. - **"Run AWS services in our own data center"** → **AWS Outposts**. - **"Same physical AZ across two accounts"** → compare **AZ IDs**, not AZ names. "Highly available" on the exam almost always means **at least two AZs**. One AZ is a single point of failure, even if it holds many servers. ## Common traps [#common-traps] - **"Deploy to multiple Regions" for plain high availability.** Multi-AZ is enough and much cheaper. Multi-Region is for Region-wide failures, DR in another geography, or global latency. - **"An AZ is one data center."** An AZ is *one or more* data centers. - **Running EC2 instances in edge locations.** Edge locations host CloudFront caches and DNS, not your servers. - **"IAM users are created per Region."** IAM is global. Most other services are Regional. - **Assuming every service exists in every Region.** New services and features roll out Region by Region. ## Hands-on lab: explore Regions and AZs [#hands-on-lab-explore-regions-and-azs] **Goal:** see Regions, opt-in status, AZ names and AZ IDs for your own account. Nothing in this lab creates a billable resource. AWS CloudShell has no charge. **Before you start:** sign in to the console. Select **US East (N. Virginia)** in the Region menu at the top right. ### Look at the Region menu [#look-at-the-region-menu] Open the Region menu. Note the Region codes, and that some Regions are greyed out or marked as not enabled: those are opt-in Regions. ### See which Regions are enabled [#see-which-regions-are-enabled] Open the account menu (your account name, top right) and choose **Account**. Scroll to **AWS Regions**. Each Region shows **Enabled by default**, **Enabled** or **Disabled**. Don't change anything. ### Open CloudShell [#open-cloudshell] Choose the CloudShell icon (a terminal symbol) in the console's top bar. A terminal opens at the bottom of the page, already signed in as you. ### List the Regions your account can use [#list-the-regions-your-account-can-use] ```bash aws ec2 describe-regions --all-regions \ --query "Regions[].[RegionName,OptInStatus]" --output table ``` `opt-in-not-required` means the Region is on by default. `not-opted-in` means it's an opt-in Region you haven't enabled. ### Compare AZ names and AZ IDs [#compare-az-names-and-az-ids] ```bash aws ec2 describe-availability-zones \ --query "AvailabilityZones[].[ZoneName,ZoneId,State]" --output table ``` You'll see six rows for `us-east-1`, each name paired with an ID such as `use1-az4`. If a friend runs the same command in their account, compare: in older accounts the same name can point to a different ID. ### Look at a smaller Region [#look-at-a-smaller-region] ```bash aws ec2 describe-availability-zones --region ap-southeast-2 \ --query "AvailabilityZones[].[ZoneName,ZoneId]" --output table ``` Sydney shows three AZs. **Expected result:** a table of Regions with their opt-in status, and tables of AZ names next to AZ IDs. **Clean up:** close CloudShell. Nothing else to remove. ## AWS documentation [#aws-documentation] - [AWS global infrastructure](https://aws.amazon.com/about-aws/global-infrastructure/) - [Regions and Availability Zones](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/) - [AWS Regions](https://docs.aws.amazon.com/global-infrastructure/latest/regions/aws-regions.html) - [AWS Availability Zones](https://docs.aws.amazon.com/global-infrastructure/latest/regions/aws-availability-zones.html) - [AWS services by Region](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/) - [What is AWS Local Zones?](https://docs.aws.amazon.com/local-zones/latest/ug/what-is-aws-local-zones.html) - [What is AWS Wavelength?](https://docs.aws.amazon.com/wavelength/latest/developerguide/what-is-wavelength.html) - [Amazon CloudFront key features](https://aws.amazon.com/cloudfront/features/) # Cloud Foundations (/docs/foundations) ## What cloud computing is [#what-cloud-computing-is] [Cloud computing](/docs/glossary#term-cloud-computing) is renting IT resources (servers, storage, databases, networks, software) over the internet, when you need them, and paying only for what you use. Before the cloud, a company that wanted to run a website bought servers, put them in a room it rented or owned, and paid people to keep them running. This is called running [on-premises](/docs/glossary#term-on-premises). It has three problems: - **You pay up front.** Servers cost money months before they earn any. - **You have to guess capacity.** Buy too few and the site falls over on a busy day. Buy too many and they sit idle. - **Change is slow.** Ordering, shipping and installing a new server takes weeks. The cloud fixes all three. The provider owns the data centers and the hardware. You ask for a server through a website or an API call, get it in a minute or two, and hand it back when you're done. Billing works like electricity: by the second, hour or gigabyte. A ticket-selling site is quiet most of the year, then gets 50 times its normal traffic in the hour a big concert goes on sale. On-premises, it would need to own enough servers for that one hour all year round. In the cloud, it adds servers for the sale and removes them afterwards, paying for the extra servers only during the busy hours. ## What AWS is [#what-aws-is] **Amazon Web Services (AWS)** is Amazon's cloud provider. It offers more than 200 services you can use on demand and scale up or down easily. It runs some of the biggest sites in the world, including Amazon.com itself and Netflix. ### A short history [#a-short-history]
![AWS timeline from 2002 to 2007](/diagrams/foundations-aws-history.light.svg) ![AWS timeline from 2002 to 2007](/diagrams/foundations-aws-history.dark.svg)
How AWS started, 2002 to 2007.
AWS began in 2002 as infrastructure for Amazon's own teams. In 2003 Amazon saw that running infrastructure well was one of its core strengths, and that other companies would pay for it. The first public service, the message queue Amazon SQS, came in 2004. In 2006 AWS relaunched with SQS, S3 (storage) and EC2 (servers), the three services that started the cloud as we know it, and in 2007 it opened in Europe. Since then, companies of every size have moved to AWS: start-ups such as Dropbox and Airbnb, media companies such as Netflix, and public bodies such as NASA. ### AWS in numbers [#aws-in-numbers] At the time the course slides were made, AWS had about $90 billion in yearly revenue (2023) and 31% of the cloud market (first quarter of 2024), ahead of Microsoft Azure at 25%. Gartner had named it a leader in cloud platforms for 13 years in a row, and it had more than a million active customers. These figures change every year, and the exam doesn't ask about them. What matters is that AWS is the largest cloud provider, so its services and patterns are what you'll meet at work. ### What people use AWS for [#what-people-use-aws-for] AWS isn't tied to one industry. Common uses include: - **Enterprise IT:** moving a company's internal systems out of its own data center. - **Backup and storage:** keeping copies of data far away from the office, at low cost. - **Big data analytics:** processing more data than one computer can hold. - **Websites, mobile and social apps:** serving users anywhere in the world. - **Gaming:** game servers that grow with the number of players. McDonald's, 21st Century Fox, Activision and Netflix are among the well-known companies running on AWS. ## The six advantages of cloud computing [#the-six-advantages-of-cloud-computing] AWS sums up why the cloud is worth it in six points. Learn the names: questions and answer options use the same wording.
![The six advantages of cloud computing](/diagrams/foundations-six-advantages.light.svg) ![The six advantages of cloud computing](/diagrams/foundations-six-advantages.dark.svg)
AWS's six advantages of cloud computing.
1. **Trade fixed expense for variable expense.** Pay for what you use, instead of buying data centers and servers before you know how you'll use them. A start-up pays a few dollars a month at launch, not tens of thousands for servers. 2. **Benefit from massive economies of scale.** AWS buys hardware for millions of customers, so its price per unit is lower than any one company could get alone. AWS has cut its prices many times as it has grown. 3. **Stop guessing capacity.** Add or remove resources as demand changes, instead of buying for the busiest day, like the ticket site above. 4. **Increase speed and agility.** New resources take minutes, not weeks, so teams can try ideas quickly and cheaply. A developer can test a new database for an afternoon, then delete it. 5. **Stop spending money running and maintaining data centers.** Spend time on your product, not on racking servers and cooling rooms. 6. **Go global in minutes.** Deploy in Regions around the world with a few clicks, closer to your users. A European app can add a copy in Singapore for its Asian users in a day. ## Service models: how much AWS manages [#service-models-how-much-aws-manages] Cloud services differ in how much of the stack the provider runs for you.
![Who manages each layer for on-premises, IaaS, PaaS and SaaS](/diagrams/foundations-service-models.light.svg) ![Who manages each layer for on-premises, IaaS, PaaS and SaaS](/diagrams/foundations-service-models.dark.svg)
Who manages each layer in each service model.
Each column is a stack of seven layers, from your data at the top down to the facilities at the bottom. Orange layers are yours to manage; teal layers are managed by AWS. - **On-premises:** you manage every layer, down to the building. - **[IaaS](/docs/glossary#term-iaas) (Infrastructure as a Service):** AWS runs the facilities, servers, storage and virtualisation. You manage the operating system, runtime, application and data. *Example:* Amazon EC2 gives you a virtual server and you do the rest. - **[PaaS](/docs/glossary#term-paas) (Platform as a Service):** AWS also runs the operating system and runtime. You bring your application and data. *Example:* AWS Elastic Beanstalk: you upload code and AWS runs it. - **[SaaS](/docs/glossary#term-saas) (Software as a Service):** AWS runs the whole product. You only use it and supply your data. *Example:* Amazon Rekognition: you send an image and get back what's in it. AWS Lambda is sometimes called **FaaS** (Function as a Service): you upload one function and AWS runs it when an event happens. It sits between PaaS and SaaS. The more the provider manages, the less you can change, and the less work and risk you carry. The same split decides who is responsible for security: see [the shared responsibility model](/docs/foundations/shared-responsibility). ## Deployment models: where things run [#deployment-models-where-things-run] - **Cloud:** every part of the application runs in the cloud. *Example:* a new start-up built entirely on AWS. - **[Hybrid](/docs/glossary#term-hybrid-cloud):** cloud resources connected to systems that stay on-premises. *Example:* a bank keeps its core ledger in its own data center and runs its mobile app on AWS. - **On-premises (private cloud):** resources in your own data center, often run with virtualisation tools. *Example:* a government agency that can't use a public cloud. Hybrid set-ups come up often in the exam: connecting offices to AWS (VPN, Direct Connect), syncing files (DataSync, Storage Gateway) and moving workloads over time. ## Exam tips [#exam-tips] - **"Avoid large up-front costs", "pay only for what is used"** → trade fixed expense for variable expense (on-demand pricing). - **"Unpredictable traffic", "don't want to over-provision"** → stop guessing capacity: elasticity, usually Auto Scaling. - **"Least operational overhead", "fully managed"** → the most managed option that fits, often serverless or SaaS-style services rather than EC2. - **"Must keep some systems in the company data center"** → hybrid: connect on-premises to AWS rather than moving everything. - **"Reach users worldwide with low latency"** → go global in minutes: more Regions, or edge services such as CloudFront. ## Common traps [#common-traps] - **"Run it on EC2" when the question stresses low operational overhead.** EC2 is IaaS: you patch and manage the OS. A managed or serverless service usually wins. - **Thinking the cloud means everything moves at once.** Hybrid is normal, and often the right answer for regulated data or a gradual migration. - **Picking the cheapest option when the question asks for the fastest or most reliable.** The constraint in the question decides. Cost wins only when cost is what it asks for. ## In this group [#in-this-group] ## AWS documentation [#aws-documentation] - [What is cloud computing?](https://aws.amazon.com/what-is-cloud-computing/) - [Six advantages of cloud computing](https://docs.aws.amazon.com/whitepapers/latest/aws-overview/six-advantages-of-cloud-computing.html) - [Types of cloud computing](https://docs.aws.amazon.com/whitepapers/latest/aws-overview/types-of-cloud-computing.html) # Service quotas and throttling (/docs/foundations/service-quotas) The exam guide lists "service quotas and throttling" under Task 2.2 (resilient architectures). The slides only mention quotas in passing for single services, so this page is written from the AWS documentation. ## What it is [#what-it-is] Every AWS account has limits on how much of each service it can use. AWS calls them [service quotas](/docs/glossary#term-service-quota); older documents call them *limits*. There are two kinds: - **Resource quotas:** how many of something you can have. Example: 5 VPCs per Region. - **Rate quotas:** how many requests per second you can make to an API. Going over is called [throttling](/docs/glossary#term-throttling). Quotas exist to protect you and everyone else. They stop a bug or a stolen key from launching a thousand servers on your bill, and they stop one customer from using up shared capacity. A company's Lambda functions handle orders. On Black Friday, traffic jumps tenfold and calls start failing with throttling errors. The code is fine: the account hit its Lambda concurrency quota. Raising the quota weeks before the sale would have avoided it. ## How quotas work [#how-quotas-work] - **Per account, per Region.** Unless a quota says otherwise, it applies separately in each Region. Raising the EC2 quota in `us-east-1` does nothing in `eu-west-1`. - **Default value.** Each quota starts at a default AWS sets. New accounts can start lower than the published default; AWS raises them as the account is used. - **Adjustable or not.** Many quotas can be raised on request. Some are fixed, usually because of how the service is built (for example, the maximum size of one S3 object). - **Global quotas** apply to the whole account (for example, some IAM quotas). You request changes to them in US East (N. Virginia). ### Example default quotas [#example-default-quotas] | Quota | Default | Adjustable | | --- | --- | --- | | VPCs per Region | 5 | Yes | | Elastic IP addresses per Region | 5 | Yes | | Lambda concurrent executions per Region | 1,000 | Yes | | EC2 On-Demand instances | Counted in **vCPUs** per instance family group, not number of instances | Yes | Check the **Service Quotas** console for the current values in your own account: they can differ from the defaults. ## Viewing and raising quotas [#viewing-and-raising-quotas] The **Service Quotas** console (search for "Service Quotas") shows every quota for each service, its default, the value applied to your account, and your current usage for many of them. To raise a quota: 1. Open the service in Service Quotas and select the quota. 2. Choose **Request increase at account level** and enter the new value. 3. AWS reviews the request. Small increases are often approved automatically; larger ones can take a few days. You can do the same with the CLI. Each quota has a code; `L-1216C47A` is the EC2 On-Demand standard instances quota, in vCPUs. Find any other code with `aws service-quotas list-service-quotas --service-code `. ```bash aws service-quotas request-service-quota-increase \ --service-code ec2 --quota-code L-1216C47A --desired-value 64 ``` A few services aren't in Service Quotas yet. For those, open a case in the **AWS Support Center**. ### Watching usage [#watching-usage] - **CloudWatch alarms:** for quotas that publish usage, you can create a CloudWatch alarm from the quota's page in Service Quotas. It warns you when usage passes a percentage of the quota, for example 80%. - **Trusted Advisor** also has service limit checks that flag quotas you're close to (see [Trusted Advisor](/docs/architecture/well-architected#aws-trusted-advisor)). ### Quota request templates for many accounts [#quota-request-templates-for-many-accounts] With **AWS Organizations** (all features turned on), a **quota request template** lists up to 10 quota increases. Every new account created in the organisation automatically requests those increases. Updating the template doesn't change accounts that already exist. ## Throttling [#throttling] Throttling is a rate quota in action: you send API requests faster than the service allows, so it rejects some of them. Many AWS services use a **token bucket** to decide. Picture a bucket that holds a fixed number of tokens and refills at a steady rate. Each request takes one token. A quiet period fills the bucket, so you can send a short burst. When the bucket is empty, extra requests fail until it refills. For example, EC2's read-only API calls have a bucket of 100 tokens that refills at 20 per second. When you're throttled, the call fails with an error such as `RequestLimitExceeded` (EC2), `ThrottlingException` (many other services) or HTTP status `429 Too Many Requests`. The request didn't happen, so it's safe to try again, but not straight away. ### Retry with exponential backoff and jitter [#retry-with-exponential-backoff-and-jitter]
![A throttled call retried after about 1, 2 and 4 seconds until it succeeds](/diagrams/foundations-backoff-retry.light.svg) ![A throttled call retried after about 1, 2 and 4 seconds until it succeeds](/diagrams/foundations-backoff-retry.dark.svg)
Retrying a throttled call with exponential backoff.
The same API call is tried four times, left to right. Calls 1 to 3 fail with a throttling error. Between them the client waits about 1 second, then about 2, then about 4: each wait doubles. Call 4 succeeds. Each wait also includes a small random amount (jitter). This is [exponential backoff](/docs/glossary#term-exponential-backoff): - **Exponential:** each wait is longer than the last, so a busy service gets breathing room. - **Jitter:** a little randomness in each wait, so a thousand clients that failed at the same moment don't all retry at the same moment too. **The AWS SDKs and the AWS CLI already do this for you.** If you write your own HTTP client, or call AWS from a tool that doesn't retry, you must add it yourself. ### Other ways to avoid throttling [#other-ways-to-avoid-throttling] - **Ask for a higher rate quota**, when one exists for the API. - **Spread requests out** instead of sending them all at once, for example by putting work in an SQS queue and processing it at a steady pace. - **Cache results** you read often instead of asking the API every time. - **Batch operations**, such as sending ten SQS messages in one call instead of ten calls. ## Quotas and disaster recovery [#quotas-and-disaster-recovery] The exam guide mentions "how to configure the service quotas for a workload in a standby environment". The point: quotas are per Region, so a standby Region doesn't inherit the quotas of your main Region. If your main Region runs 200 EC2 instances and your disaster recovery plan is to launch the same in a second Region, that second Region needs a quota for 200 instances' worth of vCPUs **before** the disaster. Raising quotas during an outage is slow, and everyone else is doing the same. Request the increases in the standby Region in advance, and test them. ## Exam tips [#exam-tips] - **"`ThrottlingException`", "`RequestLimitExceeded`", "429", "intermittent errors under load"** → retry with **exponential backoff and jitter**; consider a quota increase. - **"Failover to the DR Region failed because instances couldn't launch"** → the DR Region's **service quotas** weren't raised in advance. - **"Be notified before reaching a limit"** → a **CloudWatch alarm** on the quota's usage (from Service Quotas), or Trusted Advisor. - **"New accounts in the organisation need higher limits automatically"** → **Service Quotas request templates** with AWS Organizations. - **"Lambda functions are throttled during peaks"** → the concurrency quota: raise it, or use reserved or provisioned concurrency (see [Lambda concurrency](/docs/serverless/lambda-limits-concurrency#concurrency-and-throttling)). ## Common traps [#common-traps] - **"Quotas apply to the whole account across all Regions."** Most quotas are per Region. Raise them in each Region you use. - **"Retry immediately in a tight loop."** That makes throttling worse. Back off exponentially, with jitter. - **"Throttling means the service is down."** The service is fine; you're sending requests faster than your quota allows. - **"Every quota can be raised."** Some are fixed by design. Check the *Adjustable* column in Service Quotas. ## Hands-on lab: inspect your quotas [#hands-on-lab-inspect-your-quotas] **Goal:** find your account's quotas for EC2 and Lambda, and see how to set up a quota alarm. Viewing quotas is free. The optional CloudWatch alarm in the last step costs about $0.10 per month while it exists. Delete it at the end if you don't want to keep it. **Before you start:** sign in to the console in **US East (N. Virginia)**. ### Open Service Quotas [#open-service-quotas] Search for **Service Quotas** and open it. Choose **AWS services**, then search for **Amazon Elastic Compute Cloud (Amazon EC2)**. ### Find the On-Demand vCPU quota [#find-the-on-demand-vcpu-quota] Search the list for `Running On-Demand Standard`. The quota *Running On-Demand Standard (A, C, D, H, I, M, R, T, Z) instances* is measured in vCPUs. Note its **Applied account-level quota value**. A `t3.micro` uses 2 vCPUs, so divide by 2 to see how many you could run. ### Check Lambda concurrency [#check-lambda-concurrency] Go back to **AWS services** and open **AWS Lambda**. Find **Concurrent executions**. Compare the applied value with the default of 1,000. New accounts often show less. ### Do the same from CloudShell [#do-the-same-from-cloudshell] ```bash aws service-quotas list-service-quotas --service-code lambda \ --query "Quotas[?QuotaName=='Concurrent executions'].[QuotaName,Value,Adjustable]" \ --output table aws service-quotas get-aws-default-service-quota \ --service-code ec2 --quota-code L-1216C47A \ --query "Quota.[QuotaName,Value]" --output table ``` The first command shows your account's value; the second shows AWS's default for the EC2 On-Demand standard vCPU quota. ### Optional: create a quota alarm [#optional-create-a-quota-alarm] Back on the EC2 quota page from step 2, open the **Amazon CloudWatch alarms** tab and choose **Create**. Set the threshold to 80%, name it `saa-lab-ec2-vcpu-80`, and create it. In a real account you'd add an SNS email notification in CloudWatch. **Expected result:** you know your account's EC2 vCPU and Lambda concurrency quotas, and where to raise them. Don't submit an increase request unless you need one. **Clean up:** ### Delete the alarm, if you created it [#delete-the-alarm-if-you-created-it] Open **CloudWatch**, choose **Alarms**, select `saa-lab-ec2-vcpu-80` and choose **Actions → Delete**. ## AWS documentation [#aws-documentation] - [AWS service quotas](https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html) - [What is Service Quotas?](https://docs.aws.amazon.com/servicequotas/latest/userguide/intro.html) - [Requesting a quota increase](https://docs.aws.amazon.com/servicequotas/latest/userguide/request-quota-increase.html) - [Using Service Quotas request templates](https://docs.aws.amazon.com/servicequotas/latest/userguide/organization-templates.html) - [Service Quotas and Amazon CloudWatch alarms](https://docs.aws.amazon.com/servicequotas/latest/userguide/configure-cloudwatch.html) - [Request throttling for the Amazon EC2 API](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/throttling.html) - [Lambda quotas](https://docs.aws.amazon.com/general/latest/gr/lambda-service.html), [Amazon VPC quotas](https://docs.aws.amazon.com/general/latest/gr/vpc-service.html), [Amazon EC2 quotas](https://docs.aws.amazon.com/general/latest/gr/ec2-service.html) # Shared responsibility model (/docs/foundations/shared-responsibility) This topic is in the exam guide (Task 1.1) but not in the SAA slides. It's written from the AWS documentation. ## What it is [#what-it-is] The [shared responsibility model](/docs/glossary#term-shared-responsibility-model) splits the job of keeping a workload secure between AWS and you, the customer. - **AWS is responsible for security *of* the cloud:** the hardware, software, networking and buildings that run AWS services. - **You are responsible for security *in* the cloud:** what you build and store on AWS, and how you configure it. It exists because cloud security fails most often at the boundary. A company might assume "AWS handles security", leave a storage bucket open to the internet, and leak its data. AWS kept its part of the deal: the disks were safe, the buildings guarded. The open bucket was the customer's setting. Think of renting a flat. The landlord keeps the building standing, the wiring safe and the front door lock working. You decide who gets a key to your flat, and you lock your own door. If you leave it open, that's on you, not the landlord. ## How it works [#how-it-works] The line between AWS and you moves with the type of service. The more AWS manages, the less you have to secure.
![Who manages each layer for on-premises, EC2, RDS and S3/DynamoDB/Lambda](/diagrams/foundations-shared-responsibility.light.svg) ![Who manages each layer for on-premises, EC2, RDS and S3/DynamoDB/Lambda](/diagrams/foundations-shared-responsibility.dark.svg)
Who secures each layer, by type of service.
The grid has seven layers as rows, from "your data, IAM access, encryption" at the top to "buildings, power, cooling" at the bottom, and four columns: - **On-premises:** you manage every layer. - **Amazon EC2:** AWS manages the hardware and the buildings. You manage everything from the operating system up: OS patches, installed software, security group rules, your application and your data. - **Amazon RDS:** AWS also patches the operating system and the database engine. You still manage the database settings, the security groups, who can connect, and your data. - **S3, DynamoDB, Lambda:** AWS runs everything below your data, code and permissions. There are no servers or security groups for you to manage (Lambda in a VPC is the exception: see [Lambda networking](/docs/serverless/lambda-networking#lambda-in-a-vpc)). The top two rows are always yours, whatever the service: **your data, who can access it, whether it's encrypted, and how your application is configured.** ## AWS's side: security of the cloud [#awss-side-security-of-the-cloud] AWS protects the infrastructure that runs every service: - **Physical security:** the data centers, guards, access control, power, cooling and fire protection. - **Hardware:** servers, storage devices and network gear, including replacing failed parts and securely wiping disks before they leave. - **The global network:** the fibre between Regions and AZs, and its protection. - **The virtualisation layer:** keeping one customer's virtual machines isolated from another's on the same physical host. - **The software of managed services:** for services like RDS, S3 and DynamoDB, the operating system and platform underneath. You can't inspect AWS's data centers yourself. Instead, AWS has them audited by third parties and publishes the reports (SOC, ISO 27001, PCI DSS and more) through **[AWS Artifact](/docs/security/detective-security-hub-artifact#aws-artifact)**. ## Your side: security in the cloud [#your-side-security-in-the-cloud] What you're responsible for depends on the service, but it always includes: - **Your data:** what you store, how it's classified, and whether it's encrypted at rest and in transit. - **Identity and access:** IAM users, roles and policies, MFA, and who can reach what. - **Configuration:** bucket policies, security groups, network ACLs, public or private settings. - **For IaaS such as EC2, also:** the guest operating system and its patches, any software you install, and host firewall rules. AWS gives you the tools to do your part (IAM, KMS encryption, security groups, logging with CloudTrail), but turning them on and setting them up correctly is your job. ## Three kinds of controls [#three-kinds-of-controls] AWS describes three ways a security control can be split: - **Inherited controls** come entirely from AWS; you have nothing to do. *Example:* physical and environmental controls such as guards, locks, power and cooling. - **Shared controls** are the same kind of work, done by each side at its own layer: - *Patch management:* AWS patches the infrastructure; you patch your guest OS and applications. - *Configuration management:* AWS configures its devices; you configure your OS, databases and apps. - *Awareness and training:* AWS trains its staff; you train yours. - **Customer-specific controls** are entirely yours, because they depend on what you build. *Example:* service and communications protection, or "zone security": routing data inside security environments you design. ## The same tasks on three services [#the-same-tasks-on-three-services] The split changes how much work a task is. Here is who does what for a few common tasks. ### On Amazon EC2 [#on-amazon-ec2] - **OS patches:** you. - **Firewall rules:** you, with security groups. - **Encryption at rest:** you turn on EBS encryption. - **Backups:** you take snapshots. ### On Amazon RDS [#on-amazon-rds] - **OS and database engine patches:** AWS, in a maintenance window you choose. - **Firewall rules:** you, with security groups. - **Encryption at rest:** you choose it when you create the database. - **Backups:** automated backups are on by default; you set how long to keep them. ### On Amazon S3 [#on-amazon-s3] - **OS patches:** AWS. There's no OS for you to see. - **Access rules:** you, with IAM, bucket policies and Block Public Access. - **Encryption at rest:** on by default (SSE-S3); you choose the key type. - **Protection against deletion:** you turn on versioning and replication. On all three, **who can access the data is always your job**: IAM permissions, and on EC2 also SSH keys, on RDS also database users. ## Real-world examples [#real-world-examples] - **A leaked database dump:** a developer puts a backup in an S3 bucket and makes the bucket public "for a minute". It gets indexed and copied. S3 worked as designed; the access setting was the customer's responsibility. - **An unpatched server:** a company runs an old web server on EC2 and never updates the OS. Attackers use a known flaw to get in. On EC2, OS patching is the customer's job. - **A managed database:** a team moves the same database from EC2 to RDS. They no longer patch the OS or the database engine, so a whole class of risk moves to AWS. They still control who can connect and whether the storage is encrypted. ## Exam tips [#exam-tips] - **"Who patches the guest OS on EC2?"** → the customer. - **"Who patches the OS or database engine for RDS?"** → AWS. - **"Physical security of data centers", "decommissioning disks"** → AWS. - **"Encrypting data", "IAM permissions", "security group rules"** → the customer, on every service. - **"Reduce the operational burden of security patching"** → move to a managed or serverless service (RDS, Fargate, Lambda). - **"Proof of AWS's compliance", "SOC or PCI reports"** → AWS Artifact. When a question asks how to *reduce* what you have to secure, the answer is usually a more managed service. Moving from EC2 to RDS, or from EC2 to Lambda, shifts patching to AWS. ## Common traps [#common-traps] - **"AWS encrypts and protects my data automatically, so I don't need to configure anything."** AWS gives you encryption and access tools; choosing, enabling and configuring them is your job. - **"AWS patches the OS on my EC2 instances."** Not on EC2. AWS patches the host, not your guest OS. - **"With managed services, security is entirely AWS's job."** Your data, IAM permissions and settings are always yours. - **"The customer must audit AWS data centers."** Customers can't. They rely on AWS's third-party audit reports in AWS Artifact. ## Check yourself [#check-yourself] This page is a concept with nothing to build, so instead of a lab, test yourself: The customer. On EC2, the guest operating system is the customer's responsibility. If the company moved MySQL to Amazon RDS, AWS would install it. The customer's. Bucket policies, ACLs and Block Public Access settings are configuration, which is security in the cloud. AWS. Hardware and its secure disposal are part of security of the cloud. Patch management: AWS patches the infrastructure and the managed-service software; the customer patches its guest operating systems and applications. Configuration management and awareness/training are also shared. ## AWS documentation [#aws-documentation] - [Shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) - [Shared responsibility model in the Well-Architected security pillar](https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/shared-responsibility.html) # Glossary (/docs/glossary) # Access keys (/docs/identity/access-keys) ## What it is [#what-it-is] An [access key](/docs/glossary#term-access-key) is a pair of values that lets the AWS CLI, an SDK or a direct API call act as an IAM user: - The **access key ID** works like a user name, for example `AKIAIOSFODNN7EXAMPLE`. - The **secret access key** works like a password. AWS shows it **once**, when you create the key, and never again. Access keys exist because programs can't type a password and an MFA code into a web page. They sign each API request instead. The [Console, CLI and SDK](/docs/foundations/console-cli-sdk) page shows where access keys fit among the ways to reach AWS. ## How access keys work [#how-access-keys-work] - You create them in the IAM console, on the user's **Security credentials** tab. Users can manage their own keys if their policy allows it. - Each IAM user can have **at most two** access keys. Two lets you rotate: create the new key, switch your programs to it, then delete the old one. - A key is **Active** or **Inactive**. Deactivating stops it working at once but keeps it, so you can turn it back on if something breaks. Deleting is permanent. - The console shows when each key was **last used**, from which Region and for which service. Unused keys are a risk: delete them. - Keys don't expire by themselves. They work until someone deactivates or deletes them. Anyone with your access key ID and secret can do everything your user can, from anywhere in the world. Never share them, never put them in code or in a git repository, and never store them on an EC2 instance. ## Better than access keys [#better-than-access-keys] AWS now recommends avoiding long-term access keys wherever possible: - **On your own computer:** `aws login` with your console sign-in, or IAM Identity Center with `aws configure sso`. Both give short-term credentials that expire by themselves. - **On EC2, Lambda, ECS and other AWS services:** an [IAM role](/docs/identity/roles-and-sts). The service receives temporary credentials that AWS rotates for you. - **In CI/CD outside AWS** (for example GitHub Actions): an IAM role trusted through OpenID Connect, so no keys are stored in the CI system. Access keys are a last resort for tools that support nothing else. ## Real-world examples [#real-world-examples] - **A leaked key:** a developer pushes code with an access key to a public GitHub repository. Within minutes, bots find it and start launching instances for crypto-mining. The fix: deactivate and delete the key straight away, check CloudTrail for what it did, and move the app to a role. - **Rotation:** a company with a legacy on-premises backup script still needs keys. Every 90 days it creates a second key, updates the script, confirms it works, and deletes the old key. ## Exam tips [#exam-tips] - **"An application on EC2 needs AWS credentials"** → IAM role, not access keys. - **"Access keys were exposed"** → deactivate or delete them immediately, then review activity in [CloudTrail](/docs/management/cloudtrail). - **"Rotate access keys without downtime"** → create a second key, switch over, then delete the first (two keys per user allow this). - **"Find unused or old access keys"** → IAM credential report or the key's *last used* information. - **"Access key ID ≈ user name, secret access key ≈ password"** → the way the slides frame it. ## Common traps [#common-traps] - **"Store access keys in the EC2 user data or on the instance."** Anyone who can read the instance can read them. Use a role. - **"Give the root user access keys for automation."** Root should never have access keys. - **"A user can have unlimited access keys."** The limit is two. ## Hands-on lab: create, use and remove an access key [#hands-on-lab-create-use-and-remove-an-access-key] **Goal:** see how access keys work end to end, then delete the key so it can't leak. IAM has no charge. The commands only read information. **Before you start:** have the AWS CLI installed on your computer (see the [CLI lab](/docs/foundations/console-cli-sdk#hands-on-lab-use-the-cli-two-ways)). ### Create a test user [#create-a-test-user] Open **IAM → Users → Create user**, name it `saa-cli-test`, don't give it console access, and attach the AWS managed policy `ReadOnlyAccess` directly. ### Create an access key [#create-an-access-key] Open the user → **Security credentials → Create access key**. Choose **Command Line Interface (CLI)**, read the recommendation to use alternatives, tick the confirmation and create the key. Copy both values now: the secret won't be shown again. ### Configure a CLI profile [#configure-a-cli-profile] ```bash aws configure --profile saa-cli-test ``` Paste the access key ID and secret, set the Region to `us-east-1` and the output to `json`. ### Use it [#use-it] ```bash aws sts get-caller-identity --profile saa-cli-test aws s3 ls --profile saa-cli-test aws iam create-user --user-name should-fail --profile saa-cli-test ``` The first two work. The last one fails with `AccessDenied`: the user only has read access. ### Deactivate, then delete [#deactivate-then-delete] In the console, set the key to **Inactive** and run `aws sts get-caller-identity --profile saa-cli-test` again: it now fails. Then delete the key and the `saa-cli-test` user. **Expected result:** read-only calls succeed, a write call is denied, and the key stops working as soon as it's deactivated. **Clean up:** delete the access key and the `saa-cli-test` user (done above), then remove the profile from `~/.aws/credentials` and `~/.aws/config`. ## AWS documentation [#aws-documentation] - [Manage access keys for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) - [Best practices for managing AWS access keys](https://docs.aws.amazon.com/accounts/latest/reference/credentials-access-keys-best-practices.html) - [Generate credential reports](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html) # Amazon Cognito (/docs/identity/cognito) ## What it is [#what-it-is] [Amazon Cognito](/docs/glossary#term-amazon-cognito) gives the **users of your web and mobile apps** an identity: a way to sign up, sign in and, if needed, reach AWS resources directly. It has two parts: - **[User pools](/docs/glossary#term-user-pool):** a user directory and sign-in service for your app. Users sign in with a username or email and password, or with Google, Facebook, Apple, SAML or OIDC, and get tokens your app and APIs can trust. - **[Identity pools](/docs/glossary#term-identity-pool)** (also called federated identities): swap a token from a user pool or another identity provider for **temporary AWS credentials**, so the app can call AWS services such as S3 or DynamoDB directly. Cognito exists because IAM isn't built for app customers. You'd never create an IAM user for each of a million shoppers. Cognito scales to millions of users, handles password resets and MFA, and gives each user only narrow, temporary access. ## Cognito user pools [#cognito-user-pools] A user pool is a **serverless database of users** for your app, with everything around sign-in built in: - Sign-up and sign-in with username (or email) and password, and **password reset**. - **Email and phone number verification**. - **MFA**, including authenticator apps, and on higher plans passwordless sign-in with passkeys or one-time codes. - **Federated sign-in** with social providers (Google, Facebook, Apple, Amazon), SAML 2.0 and OpenID Connect providers. - **Managed login:** a ready-made, customisable sign-in page, so you don't have to build one. After sign-in, the user pool issues **JSON Web Tokens (JWTs)** that prove who the user is. ### User pool integrations [#user-pool-integrations]
![The app signs in to the Cognito user pool, then calls API Gateway with the token, which is verified before the backend runs](/diagrams/identity-cognito-user-pools.light.svg) ![The app signs in to the Cognito user pool, then calls API Gateway with the token, which is verified before the backend runs](/diagrams/identity-cognito-user-pools.dark.svg)
A user pool protecting an API.
1. The user signs in to the **Cognito user pool** and the app receives a token. 2. The app calls the API (on **API Gateway**, or behind an **Application Load Balancer**) and passes the token. 3. API Gateway (or the ALB) **verifies the token** against the user pool. Invalid or expired tokens are rejected. 4. Valid requests reach the **backend**, such as a Lambda function or EC2 instances. With an ALB, the listener rule authenticates the user with Cognito before forwarding to the target group. Either way, your backend code doesn't need to check passwords itself. ## Cognito identity pools [#cognito-identity-pools] Identity pools give app users **temporary AWS credentials**, so the app can call AWS services directly instead of going through your own backend.
![The app logs in to an identity provider, swaps the token at the identity pool for temporary AWS credentials, and uses them to reach S3 or DynamoDB](/diagrams/identity-cognito-identity-pools.light.svg) ![The app logs in to an identity provider, swaps the token at the identity pool for temporary AWS credentials, and uses them to reach S3 or DynamoDB](/diagrams/identity-cognito-identity-pools.dark.svg)
An identity pool handing out AWS credentials.
1. The user logs in to an **identity provider**: a Cognito user pool, Google, Facebook, a SAML or OIDC provider. The app gets a token. 2. The app sends the token to the **Cognito identity pool**, which validates it with the provider and returns **temporary AWS credentials** (through STS). 3. The app uses those credentials to reach **S3, DynamoDB** or other services directly. How permissions work: - The IAM policies behind the credentials are defined **in Cognito**, as IAM roles. - There's a **default role for authenticated users** and another for **guest (unauthenticated) users**, if you allow guests. - Rules can pick a different role per user, and policies can use the user's ID for **fine-grained control**. ### Row-level security in DynamoDB [#row-level-security-in-dynamodb] This policy lets each user read and write only the DynamoDB items whose partition key equals **their own Cognito identity ID**: ```json { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "dynamodb:GetItem", "dynamodb:BatchGetItem", "dynamodb:Query", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem", "dynamodb:BatchWriteItem" ], "Resource": ["arn:aws:dynamodb:us-west-2:123456789012:table/MyTable"], "Condition": { "ForAllValues:StringEquals": { "dynamodb:LeadingKeys": ["${cognito-identity.amazonaws.com:sub}"] } } }] } ``` `${cognito-identity.amazonaws.com:sub}` is replaced at request time by the caller's identity ID. A user can never read someone else's rows, even though everyone uses the same table and the same role. The same idea works for S3, with a folder per user. ## User pools vs identity pools [#user-pools-vs-identity-pools] | | User pool | Identity pool | | --- | --- | --- | | Answers | Who is this user? | What AWS access do they get? | | Gives the app | Tokens (JWTs) | Temporary AWS credentials | | Typical use | Sign-in, protect your API | Direct access to S3, DynamoDB | They're often used together: the user pool signs users in, and the identity pool turns that sign-in into AWS credentials. ## Pricing [#pricing] User pools are priced per **monthly active user** (MAU) and come in three feature plans: - **Lite:** sign-up, sign-in, social and enterprise federation, MFA. - **Essentials:** adds managed login, passwordless sign-in (passkeys, email or SMS codes), and more token customisation. - **Plus:** adds threat protection, such as risk-based adaptive authentication and compromised-credential detection. Lite and Essentials include **10,000 MAU free every month**, and this free allowance doesn't expire after the first year. Identity pools themselves have no charge. The feature plans (Lite, Essentials, Plus), managed login and passkey support are newer than the course slides. The core ideas, user pools for sign-in and identity pools for AWS credentials, haven't changed. ## Cognito vs IAM [#cognito-vs-iam] The course's rule of thumb for spotting Cognito in a question: - **"Hundreds of users", "mobile users", "web app users", "authenticate with SAML / Google / Facebook"** → Cognito. - **People and workloads managing your AWS account** → IAM (or IAM Identity Center). ## Exam tips [#exam-tips] - **"Add sign-up and sign-in to a web or mobile app"** → Cognito user pool. - **"Authenticate API Gateway requests with app users"** → Cognito user pool authorizer. - **"Authenticate users at an Application Load Balancer"** → ALB with Cognito authentication. - **"Mobile app users need direct access to S3 / DynamoDB"** → Cognito identity pool (temporary credentials). - **"Each user can only access their own items / folder"** → identity pool + policy variable `${cognito-identity.amazonaws.com:sub}`. - **"Guest access to AWS resources"** → identity pool with unauthenticated identities. ## Common traps [#common-traps] - **"Create an IAM user for each app user."** Doesn't scale and isn't safe. Use Cognito. - **Mixing up the pools.** User pools sign users in; identity pools hand out AWS credentials. - **"Cognito is for employee single sign-on to AWS accounts."** That's IAM Identity Center. ## Hands-on lab: a user pool with managed login [#hands-on-lab-a-user-pool-with-managed-login] **Goal:** create a user pool, sign up through Cognito's managed login page, and see the user appear. Under 10,000 monthly active users on the Lite or Essentials plan, a user pool costs nothing. ### Create the user pool [#create-the-user-pool] Open **Amazon Cognito → User pools → Create user pool**. Choose application type **Single-page application (SPA)**, name the app `saa-lab-app`, sign-in identifier **Email**, required attribute **email**, and add a return URL `https://localhost:3000`. Create the pool. ### Open the managed login page [#open-the-managed-login-page] In the new pool, open **App clients → saa-lab-app → View login page**. A hosted sign-in page opens. ### Sign up [#sign-up] Choose **Create an account**, enter your email and a password, and confirm the code Cognito emails you. After sign-in, the browser goes to `https://localhost:3000/?code=…` and shows an error page: that's expected, there's no app running. The `code` in the address is what a real app would exchange for tokens. ### See the user [#see-the-user] Back in the console, open **Users**. Your user is listed, with *Confirmation status: Confirmed* and *Email verified: Yes*. **Expected result:** a working sign-up and sign-in flow without writing any code, and a confirmed user in the pool. **Clean up:** delete the user pool (**User pools → select → Delete**; you may need to turn off deletion protection first). ## AWS documentation [#aws-documentation] - [What is Amazon Cognito?](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) - [Amazon Cognito user pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools.html) - [Amazon Cognito identity pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) - [Control access to API Gateway with a Cognito user pool](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) - [Authenticate users using an Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-authenticate-users.html) - [Amazon Cognito pricing](https://aws.amazon.com/cognito/pricing/) # AWS Control Tower (/docs/identity/control-tower) ## What it is [#what-it-is] [AWS Control Tower](/docs/glossary#term-aws-control-tower) sets up and runs a **secure, compliant multi-account environment** based on AWS best practices. It builds on AWS Organizations: Control Tower creates the organization, the accounts and the policies for you, then keeps watching them. It exists because building a good multi-account set-up by hand takes weeks: OUs, a log archive account, an audit account, central CloudTrail, AWS Config everywhere, SCPs, single sign-on. Control Tower does it in under an hour. ## How it works [#how-it-works] Control Tower has four main parts: - **[Landing zone](/docs/glossary#term-landing-zone):** the multi-account environment it builds, with a *Security* OU holding a **log archive account** (central logs) and an **audit account** (security tools), plus OUs for your workloads. It turns on CloudTrail and AWS Config across accounts and sets up IAM Identity Center. - **Account Factory:** a template for creating new accounts that already follow your standards (network settings, Regions, controls). Teams can request accounts that are compliant from day one. - **Controls:** rules applied to OUs that keep accounts compliant. *(The course and older material call them **guardrails**; AWS now calls them **controls**.)* - **Dashboard:** shows accounts, OUs, enabled controls and any non-compliant resources. ## Controls [#controls]
![Preventive, detective and proactive controls and how each is built](/diagrams/identity-control-tower-controls.light.svg) ![Preventive, detective and proactive controls and how each is built](/diagrams/identity-control-tower-controls.dark.svg)
The three kinds of Control Tower controls.
- **Preventive controls** stop an action from happening. They're built with **SCPs** (and RCPs). *Example:* deny the use of Regions outside the approved list in every account. - **Detective controls** find resources that break a rule after they exist. They're built with **[AWS Config rules](/docs/management/config#config-rules)**. *Example:* find resources without the required tags. - **Proactive controls** check resources **before** they're deployed with CloudFormation, using **CloudFormation hooks**. *Example:* reject a template that creates an unencrypted S3 bucket. Each control is also labelled by guidance: - **Mandatory:** always on and can't be turned off (for example, protecting the log archive). - **Strongly recommended:** best practice for most companies. - **Elective:** for specific needs. Controls apply to a whole OU. The management account isn't covered by them. ### Example: fixing untagged resources [#example-fixing-untagged-resources] 1. A detective control (an AWS Config rule) watches member accounts for untagged resources. 2. When it finds one, the resource is marked **NON_COMPLIANT** and an SNS notification is sent. 3. SNS emails the admin and invokes a Lambda function. 4. The Lambda function adds the missing tags to the resource. ## Organizations vs Control Tower [#organizations-vs-control-tower] - **AWS Organizations** is the building block: accounts, OUs, consolidated billing, SCPs. You design and maintain everything yourself. - **AWS Control Tower** is the ready-made house built from those blocks: a best-practice landing zone, an account factory and a library of controls, managed for you. ## Exam tips [#exam-tips] - **"Set up a multi-account environment quickly, following best practices"** → AWS Control Tower. - **"Automatically create new accounts that comply with company standards"** → Control Tower Account Factory. - **"Preventive guardrail"** → SCP. **"Detective guardrail"** → AWS Config rule. **"Proactive"** → CloudFormation hook. - **"Monitor compliance across accounts on a dashboard"** → Control Tower. ## Common traps [#common-traps] - **"Control Tower replaces Organizations."** It runs on top of Organizations. - **"Detective controls stop the action."** They only find and report it; preventive controls stop it. ## Check yourself [#check-yourself] There's no lab for Control Tower: setting up a landing zone creates extra accounts and turns on paid services (AWS Config, CloudTrail) across them, and it takes time to undo. Test your understanding instead: A preventive control, implemented with an SCP that denies requests to other Regions. A detective control, implemented with an AWS Config rule. It finds and reports the buckets; a remediation (for example a Lambda function) can fix them. Control Tower Account Factory. ## AWS documentation [#aws-documentation] - [What is AWS Control Tower?](https://docs.aws.amazon.com/controltower/latest/userguide/what-is-control-tower.html) - [About controls in AWS Control Tower](https://docs.aws.amazon.com/controltower/latest/userguide/controls.html) - [How controls work](https://docs.aws.amazon.com/controltower/latest/userguide/how-controls-work.html) - [Provision and manage accounts with Account Factory](https://docs.aws.amazon.com/controltower/latest/userguide/account-factory.html) # AWS Directory Service (/docs/identity/directory-service) ## What it is [#what-it-is] **Microsoft Active Directory (AD)** is the directory most companies use to manage their Windows users and computers. It runs on Windows Server with **AD Domain Services** and stores *objects*: user accounts, computers, printers, file shares and security groups. Servers called **domain controllers** check passwords and hand out permissions, so a user like John signs in once and can use any machine on the company network. Objects are organised in **trees**, and a group of trees is a **forest**. **[AWS Directory Service](/docs/glossary#term-aws-directory-service)** brings AD to AWS in three ways, so that Windows workloads, IAM Identity Center and other AWS services can use AD identities. ## How it works [#how-it-works]
![AWS Managed Microsoft AD trusts an on-premises AD, AD Connector forwards sign-ins to it, and Simple AD stands alone](/diagrams/identity-directory-options.light.svg) ![AWS Managed Microsoft AD trusts an on-premises AD, AD Connector forwards sign-ins to it, and Simple AD stands alone](/diagrams/identity-directory-options.dark.svg)
The three Directory Service options.
### AWS Managed Microsoft AD [#aws-managed-microsoft-ad] A **real Microsoft AD** that AWS runs for you, across two Availability Zones. - Users are created and managed **in AWS**, and it supports MFA. - It can set up a **trust** with your on-premises AD (one-way or two-way), so users from either side can reach resources on the other. - Editions: **Standard** (for up to about 5,000 employees, 30,000 objects) and **Enterprise** (up to about 500,000 objects). - *Use it when:* you need AD-aware apps on AWS (SQL Server, SharePoint, Windows file shares with FSx), or a directory in AWS that keeps working if the link to on-premises fails. ### AD Connector [#ad-connector] A **proxy** (directory gateway) that forwards sign-in requests to your **on-premises AD**. - **No users are stored in AWS**: they stay in the on-premises AD. - Supports MFA through your existing RADIUS server. - Sizes are small and large, with no user limit. - *Use it when:* you just want AWS services (IAM Identity Center, WorkSpaces, the AWS console) to use your existing AD accounts, without copying them. ### Simple AD [#simple-ad] An **AD-compatible** directory, based on Samba 4, managed by AWS. - Can't be joined with an on-premises AD (no trusts), and has no MFA. - Small (up to 500 users) and large (up to 5,000 users). **Simple AD is no longer open to new customers.** It may still appear in exam questions as a low-cost, standalone directory, but for new set-ups use AWS Managed Microsoft AD. ## Using AD with IAM Identity Center [#using-ad-with-iam-identity-center] - **AWS Managed Microsoft AD:** connect it to IAM Identity Center directly. It works out of the box. - **Self-managed AD (on-premises or on EC2):** either create a **two-way trust** between it and an AWS Managed Microsoft AD and connect that, or put an **AD Connector** in front of it and connect the connector. ## Compared side by side [#compared-side-by-side] - **AWS Managed Microsoft AD:** users stored in AWS; linked to on-premises AD by a **trust**; supports MFA. - **AD Connector:** users stay **on-premises**; works as a **proxy**; MFA through your RADIUS server. - **Simple AD:** users stored in AWS; **no link** to on-premises; no MFA. ## Exam tips [#exam-tips] - **"Users must be managed in AWS, with a trust to on-premises AD"** → AWS Managed Microsoft AD. - **"Use existing on-premises AD users without storing them in AWS"** → AD Connector. - **"Low-cost, standalone, AD-compatible directory, no on-premises link"** → Simple AD. - **"Run AD-aware apps such as SQL Server or SharePoint on AWS"** → AWS Managed Microsoft AD. - **"Single sign-on to AWS accounts with AD users"** → IAM Identity Center connected to Managed Microsoft AD or AD Connector. ## Common traps [#common-traps] - **"AD Connector caches or copies users to AWS."** It stores none; it only forwards requests. - **"Simple AD can trust an on-premises AD."** It can't. ## Check yourself [#check-yourself] There's no lab here: every Directory Service option is billed per hour from the moment it's created (AWS Managed Microsoft AD costs well over $100 a month), and it needs a VPC with two subnets. Test yourself instead: AD Connector, connected to IAM Identity Center. AWS Managed Microsoft AD, with a trust to the on-premises AD. ## AWS documentation [#aws-documentation] - [What is AWS Directory Service?](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/what_is.html) - [AWS Managed Microsoft AD](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_microsoft_ad.html) - [AD Connector](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_ad_connector.html) - [Simple Active Directory](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_simple_ad.html) - [Connect to a Microsoft AD directory (IAM Identity Center)](https://docs.aws.amazon.com/singlesignon/latest/userguide/manage-your-identity-source-ad.html) # IAM Identity Center (/docs/identity/iam-identity-center) ## What it is [#what-it-is] [AWS IAM Identity Center](/docs/glossary#term-iam-identity-center) (the successor to **AWS Single Sign-On**) gives your workforce **one sign-in** for: - every **AWS account** in your AWS organization; - **business cloud apps** such as Salesforce, Box and Microsoft 365; - any app that supports **SAML 2.0**; - **EC2 Windows instances** (remote desktop). It's AWS's recommended way for people to access AWS. Instead of an IAM user in every account, each person has one identity, signs in once to an **AWS access portal**, and picks the account and role they need. The credentials they get are temporary. IAM Identity Center has no extra charge. ## How it works [#how-it-works]
![An employee signs in once to IAM Identity Center, which gives access to AWS accounts, EC2 Windows and business apps; users come from one identity source](/diagrams/identity-identity-center.light.svg) ![An employee signs in once to IAM Identity Center, which gives access to AWS accounts, EC2 Windows and business apps; users come from one identity source](/diagrams/identity-identity-center.dark.svg)
One sign-in, many accounts and apps.
1. An employee opens the AWS access portal URL and signs in once. 2. IAM Identity Center checks their identity against the **identity source** (bottom of the diagram). 3. Based on their **assignments**, the portal lists the AWS accounts and apps they may use. 4. They choose an account and a **permission set**, and get either a console session or temporary CLI credentials (`aws configure sso`). ### Identity sources [#identity-sources] You choose **one** source of users and groups: - **The Identity Center directory:** users and groups created in Identity Center itself. Good for small companies. - **Active Directory:** AWS Managed Microsoft AD, or your on-premises AD through an AD Connector. See [Directory Service](/docs/identity/directory-service). - **An external identity provider** such as Okta, Microsoft Entra ID or OneLogin, connected with SAML 2.0 (users can be synced automatically with SCIM). ### Organization and account instances [#organization-and-account-instances] - An **organization instance** is enabled in the management account of an AWS organization. It's the recommended kind and the **only** kind that can give access to AWS accounts. - An **account instance** belongs to a single account and is used only for some AWS managed applications in isolated set-ups. ## Permission sets and assignments [#permission-sets-and-assignments] A **[permission set](/docs/glossary#term-permission-set)** is a collection of IAM policies (AWS managed, customer managed or inline) that defines a level of access, for example `ReadOnlyAccess` or `DatabaseAdmin`. An **assignment** links three things: **a user or group**, **a permission set**, and **one or more AWS accounts**. When you assign a permission set to an account, Identity Center creates a matching IAM role in that account. Users who sign in assume that role. *Example:* the *Developers* group gets the `FullAccess` permission set in the two dev accounts and `ReadOnlyAccess` in the two prod accounts. Bob and Alice, both in Developers, see four accounts in the portal, each with the right access. Session length for a permission set is **1 hour by default and up to 12 hours**. ## Application assignments [#application-assignments] For business apps, you assign users or groups to SAML 2.0 applications (Salesforce, Box, Microsoft 365 and others). Identity Center provides the URLs, certificates and metadata the app needs, so users reach it from the same portal without another password. ## Attribute-based access control (ABAC) [#attribute-based-access-control-abac] [ABAC](/docs/glossary#term-abac) uses **attributes of the user** stored in the identity source, such as cost center, job title or locale, inside permission policies. Define the permissions once, then change someone's access by changing their attributes, not the policies. *Example:* a policy allows access to resources whose `CostCenter` tag matches the user's `CostCenter` attribute. Moving someone to another team updates their attribute, and their access follows. ## Real-world examples [#real-world-examples] - **A company with 40 AWS accounts** connects Identity Center to Microsoft Entra ID. Employees sign in with their work account, and leavers lose access to every AWS account the moment they're disabled in Entra ID. - **A database team** gets a `DBAdmin` permission set assigned to the RDS and Aurora accounts only. ## Exam tips [#exam-tips] - **"Single sign-on to multiple AWS accounts"**, **"central management of workforce access"** → IAM Identity Center. - **"Users already exist in Active Directory / Okta / Entra ID"** → Identity Center with that identity source. - **"A collection of policies assigned to users for an account"** → permission set. - **"Permissions based on user attributes such as department"** → ABAC. - **"Single sign-on to business apps like Salesforce or Microsoft 365"** → Identity Center application assignments. ## Common traps [#common-traps] - **Confusing it with Cognito.** Identity Center is for your **employees**; Cognito is for your **app's customers**. - **"Create IAM users in every account for each employee."** That's what Identity Center replaces. - **"Simple AD can be the identity source."** It can't; use the Identity Center directory, AWS Managed Microsoft AD, AD Connector or an external IdP. ## Hands-on lab: sign in through the access portal [#hands-on-lab-sign-in-through-the-access-portal] **Goal:** enable IAM Identity Center, create a user with a permission set, and sign in through the portal. IAM Identity Center has no charge. It needs an AWS organization, which is also free; your account becomes its management account. **Before you start:** use `us-east-1`. If you deleted the organization from the [Organizations lab](/docs/identity/organizations-scps#hands-on-lab-create-an-organization-and-an-scp), that's fine: enabling Identity Center creates a new one. ### Enable IAM Identity Center [#enable-iam-identity-center] Open **IAM Identity Center → Enable**, and confirm it should create an organization instance. Note the **AWS access portal URL** on the dashboard. ### Create a user and group [#create-a-user-and-group] Open **Users → Add user**: user name `saa-portal`, your email (the address can use a `+` alias, for example `you+saa@example.com`). Create a group `Readers` and add the user. Accept the email invitation and set a password. ### Create a permission set [#create-a-permission-set] Open **Permission sets → Create**: predefined `ReadOnlyAccess`, session duration 1 hour. ### Assign it [#assign-it] Open **AWS accounts**, tick your account, choose **Assign users or groups**, pick `Readers`, then `ReadOnlyAccess`, and submit. ### Sign in [#sign-in] In a private window, open the access portal URL and sign in as `saa-portal` (set up MFA when asked). Your account appears with `ReadOnlyAccess`. Open the console from it: you can view, not change. The **Access keys** link next to it gives temporary CLI credentials. **Expected result:** one sign-in leads to your account with read-only access, and IAM in your account now has a role named `AWSReservedSSO_ReadOnlyAccess_…` created by Identity Center. **Clean up:** remove the assignment, delete the permission set, user and group. Optionally delete the instance (**Settings → Delete**) and then the organization. ## AWS documentation [#aws-documentation] - [What is IAM Identity Center?](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) - [Manage your identity source](https://docs.aws.amazon.com/singlesignon/latest/userguide/manage-your-identity-source.html) - [Permission sets](https://docs.aws.amazon.com/singlesignon/latest/userguide/permissionsetsconcept.html) - [Attribute-based access control](https://docs.aws.amazon.com/singlesignon/latest/userguide/abac.html) - [Organization and account instances of IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/identity-center-instances.html) # Identity & Access (/docs/identity) ## What it is [#what-it-is] Every request to AWS answers two questions: 1. **Who are you?** This is *authentication*: proving your identity with a password, MFA code, access key or token. 2. **What are you allowed to do?** This is *authorization*: checking your permissions for this action on this resource. [AWS Identity and Access Management](/docs/glossary#term-iam) (IAM) answers both for one AWS account. It's a **global** service (you don't pick a Region) and it's **free**: you pay only for the resources your users create. As a company grows, one account isn't enough. The rest of this group covers the services that manage identity across many accounts (Organizations, Control Tower, IAM Identity Center), connect to a company directory (Directory Service), share resources between accounts (RAM), and sign in the users of your own apps (Cognito). ## The building blocks of IAM [#the-building-blocks-of-iam] - **[Root user](/docs/glossary#term-root-user):** the identity created with the account, signed in with the account's email address. It can do everything, so you lock it away and use it only for the few tasks that need it. - **[IAM users](/docs/glossary#term-iam-user):** long-term identities for people or, rarely, applications. Each has its own password for the console and, if needed, access keys for the CLI. - **[IAM groups](/docs/glossary#term-iam-group):** collections of users. Permissions given to a group apply to every user in it. Groups contain only users, never other groups. - **[IAM roles](/docs/glossary#term-iam-role):** identities with no long-term credentials. Users, applications and AWS services *assume* a role to get temporary credentials. - **[Policies](/docs/glossary#term-iam-policy):** JSON documents that say which actions are allowed or denied on which resources. They're attached to users, groups and roles, or to resources such as S3 buckets. A small company has five developers and two operations engineers. It creates a *Developers* group and an *Operations* group, attaches a policy to each, and adds every person as a user in the right group. When someone joins, they're added to a group and get the right access at once. When they leave, their user is deleted. Applications on EC2 don't get users at all: they use a role. ## In this group [#in-this-group] ### IAM basics [#iam-basics] ### Advanced IAM [#advanced-iam] ### Many accounts [#many-accounts] ### App users [#app-users] ## Which service for which identity? [#which-service-for-which-identity] - **People in your company, one account** → IAM users and groups (or IAM Identity Center). - **People in your company, many accounts** → IAM Identity Center with AWS Organizations. - **Your company already uses Microsoft Active Directory** → connect it with AWS Directory Service and IAM Identity Center. - **An application running on AWS** (EC2, Lambda, ECS) → an IAM role. - **Another AWS account** → a cross-account IAM role, or a resource-based policy. - **Customers using your web or mobile app** (thousands or millions of them) → Amazon Cognito. ## Exam tips [#exam-tips] - **"Global service", "not tied to a Region"** → IAM (so are Organizations, Route 53 and CloudFront). - **"Grant an EC2 instance or Lambda function access to S3 / DynamoDB"** → an IAM role, never access keys. - **"Many accounts", "central management", "consolidated billing"** → AWS Organizations. - **"Single sign-on for employees across accounts"** → IAM Identity Center. - **"Hundreds of thousands of users", "mobile app users", "sign in with Google / Facebook"** → Amazon Cognito, not IAM. ## Common traps [#common-traps] - **Creating IAM users for app customers.** IAM is for people and workloads that manage AWS. App customers belong in Cognito. - **Using the root user for daily work.** Root is for a short list of account-level tasks only. - **Putting groups inside groups.** IAM groups can't be nested. ## AWS documentation [#aws-documentation] - [What is IAM?](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) - [IAM identities](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html) - [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) # Root user, MFA and passwords (/docs/identity/mfa-password-policy) ## What it is [#what-it-is] Anyone who signs in to your account can change settings or delete resources. Three controls make sign-ins safer: - Locking away the **[root user](/docs/glossary#term-root-user)**, the one identity that can do everything. - An account **[password policy](/docs/glossary#term-password-policy)** that forces IAM users to choose strong passwords. - **[Multi-factor authentication](/docs/glossary#term-mfa) (MFA)**: something you know (a password) plus something you have (a phone app or a security key). The main benefit of MFA: **if a password is stolen, the account is still safe**, because the attacker doesn't have your device. ## The root user [#the-root-user] The root user is created with the account and signs in with the account's email address and password. Its permissions can't be limited by IAM policies, so treat it like the master key to a building: - Don't use it for daily work. Create an IAM user or use IAM Identity Center instead. - Give it a long, unique password and turn on MFA. - Don't create access keys for it. A short list of tasks **needs** the root user, for example: - Changing the account's email address, root password or account name, and closing or reopening the account. - Restoring access when the only IAM administrator has locked themselves out. - Turning on IAM user access to the Billing console, and viewing some tax invoices. - Turning on **MFA Delete** on an S3 bucket. - Editing or deleting an S3 bucket policy or SQS queue policy that denies *every* principal, including admins. - Signing up as a seller in the EC2 Reserved Instance Marketplace. AWS now **enforces MFA for root users** of every account type (standalone, management and member accounts): you're asked to add it at account creation or at sign-in. With AWS Organizations you can also turn on **centralized root access**: the management account removes root credentials from member accounts entirely, and new member accounts are created with no root password at all. Privileged tasks such as unlocking a misconfigured bucket policy are then done centrally. ## Password policy [#password-policy] A password policy sets rules for IAM users' passwords. It doesn't apply to the root user or to access keys. **If you set nothing**, AWS's default applies: at least 8 characters, at least three of the four character types (uppercase, lowercase, numbers, symbols), not the same as the account name or email, and no expiry. **A custom policy** can: - Set a minimum length from 6 to 128 characters. - Require uppercase letters, lowercase letters, numbers and symbols. - Let users change their own password. - Make passwords expire after 1 to 1,095 days, and optionally require an administrator to reset an expired one. - Stop users reusing their last 1 to 24 passwords. IAM has no account lockout setting: repeated wrong passwords don't lock a user out. ## MFA [#mfa] With MFA turned on, signing in takes your password **and** a code or tap from a device you own. ### MFA device types [#mfa-device-types] - **Passkeys and security keys (FIDO2).** A hardware key such as a YubiKey, or a passkey synced through your phone or password manager. You tap or approve instead of typing a code. Resistant to phishing. - **Virtual authenticator apps.** An app such as Google Authenticator, Microsoft Authenticator or Authy shows a six-digit code that changes every 30 seconds. One app can hold codes for many accounts. - **Hardware TOTP tokens.** A small key fob with a screen that shows a six-digit code. Special versions exist for AWS GovCloud (US). Each root user or IAM user can register **up to 8 MFA devices**, in any mix. Registering two is a good idea, so losing one doesn't lock you out. The slides call security keys "U2F". AWS now supports the newer **FIDO2** standard, including synced **passkeys**. AWS has also ended support for SMS text-message MFA. ### Requiring MFA for actions [#requiring-mfa-for-actions] You can make a policy work only when the caller signed in with MFA, using the condition key `aws:MultiFactorAuthPresent`. This is covered with other [conditions](/docs/identity/policy-conditions-evaluation#iam-conditions). For example, a policy can allow stopping or terminating EC2 instances only for users who signed in with MFA. ## Real-world examples [#real-world-examples] - **A bank** requires a 14-character minimum, all four character types, 90-day expiry and no reuse of the last 24 passwords, to match its security standard. - **A start-up** gives every admin a YubiKey and registers a second key kept in a safe, so the root user can always be recovered. ## Exam tips [#exam-tips] - **"Protect the root user"** → strong password, MFA, no access keys, don't use it day to day. - **"Stolen password must not be enough to sign in"** → MFA. - **"Require users to use strong passwords / rotate them"** → IAM password policy. - **"Only allow an action if the user signed in with MFA"** → condition `aws:MultiFactorAuthPresent`. - **"Which task needs the root user?"** → account settings (email, closing the account), S3 MFA Delete, restoring a locked-out admin, Billing access for IAM users. ## Common traps [#common-traps] - **"Use the root user with MFA for daily admin work."** MFA makes root safer, but root still shouldn't be used day to day. - **"A password policy also protects access keys."** It only covers IAM users' console passwords. - **"SMS MFA is an option."** It's no longer supported for new set-ups. ## Hands-on lab: protect your sign-ins [#hands-on-lab-protect-your-sign-ins] **Goal:** set a password policy, then add MFA to the root user and to your IAM user. IAM and MFA have no charge. An authenticator app is free; a hardware key is optional. **Before you start:** install an authenticator app on your phone, or have a security key ready. Sign in as your IAM admin user from the [previous lab](/docs/identity/users-groups-policies#hands-on-lab-create-an-admin-user-and-group). ### Set a password policy [#set-a-password-policy] Open **IAM → Account settings → Password policy → Edit**. Choose **Custom** and set: minimum length 14, all four character types, allow users to change their own password, prevent reuse of 5 passwords. Save. ### Add MFA to your IAM user [#add-mfa-to-your-iam-user] Open **IAM → Users → your user → Security credentials → Assign MFA device**. Give it a name, choose **Authenticator app** (or **Passkey or security key**), and follow the prompts: scan the QR code and enter two codes in a row. ### Test it [#test-it] Sign out and sign back in. After your password, you're asked for the MFA code. ### Add MFA to the root user [#add-mfa-to-the-root-user] Sign in as root (email address). Open the account menu → **Security credentials** → **Assign MFA device**, and register a device the same way. Sign out of root afterwards. **Expected result:** both your IAM user and the root user ask for MFA at sign-in, and new IAM users must meet your password policy. **Clean up:** nothing to remove. Keep MFA turned on. ## AWS documentation [#aws-documentation] - [AWS account root user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) - [Tasks that require root user credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/root-user-tasks.html) - [Set an account password policy for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_account-policy.html) - [AWS Multi-factor authentication in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html) # AWS Organizations and SCPs (/docs/identity/organizations-scps) ## What it is [#what-it-is] [AWS Organizations](/docs/glossary#term-aws-organizations) is a **global** service that manages many AWS accounts as one group. - One account creates the organization and becomes the **[management account](/docs/glossary#term-management-account)**. It pays the bill and manages the organization. - The other accounts are **member accounts**. An account can belong to **only one** organization at a time. - Accounts are arranged in **[organizational units](/docs/glossary#term-organizational-unit) (OUs)**, which can be nested. - **Policies** attached to the root, an OU or an account apply to everything below it. Companies use many accounts because an account is the strongest boundary AWS has. Separate accounts for production and development mean a mistake in dev can't touch prod, each team's bill is clear, and limits (quotas) don't collide. ## How it works [#how-it-works]
![An organization with the management account, a Dev OU and a Prod OU holding nested HR and Finance OUs](/diagrams/identity-organization.light.svg) ![An organization with the management account, a Dev OU and a Prod OU holding nested HR and Finance OUs](/diagrams/identity-organization.dark.svg)
The structure of an organization.
At the top is the **root** of the organization. It holds the management account and two OUs: - **OU: Dev** contains two member accounts, Dev 1 and Dev 2. - **OU: Prod** contains two nested OUs, **HR** (two accounts) and **Finance** (one account). A policy attached to *Prod* applies to every account in HR and Finance. A policy attached to the root applies to every member account. ### Ways to arrange OUs [#ways-to-arrange-ous] - **By business unit:** Sales OU, Retail OU, Finance OU. - **By environment:** Prod OU, Dev OU, Test OU. - **By project:** Project 1 OU, Project 2 OU, Project 3 OU. Most companies mix these, for example an environment level under each business unit. OUs can be nested up to **five levels** below the root. ## Consolidated billing [#consolidated-billing] Every organization gets **consolidated billing**: - **One bill and one payment method** for all accounts, with a breakdown per account. - **Volume discounts across accounts.** Usage of services with tiered pricing (S3 storage, data transfer) is added together, so all accounts reach cheaper tiers sooner. - **Shared Reserved Instance and Savings Plans discounts.** A reservation bought in one account can apply to matching usage in another. The management account can turn this sharing off for chosen accounts. ## Other benefits [#other-benefits] - **Create accounts with an API call**, so new accounts can be automated. - **Central security and logging:** send CloudTrail logs from every account to one S3 bucket in a logging account, and CloudWatch Logs to a central account. - **Cross-account admin roles** in every member account (Organizations creates `OrganizationAccountAccessRole` in accounts it creates). - **Tag standards** for billing, enforced with tag policies. - **Multi-account vs one account with many VPCs:** separate accounts isolate better, but take more set-up. ## Service control policies (SCPs) [#service-control-policies-scps] A [service control policy](/docs/glossary#term-scp) sets the **maximum permissions** for IAM users and roles in member accounts. It looks like an IAM policy, but: - **An SCP never grants anything.** Users still need IAM policies. The SCP only limits what those policies can allow. - **SCPs don't affect the management account.** Its admins keep full power, which is one reason to run no workloads there. - **SCPs don't affect service-linked roles.** - **An action must be allowed at every level** from the root down to the account. By default, the AWS managed SCP `FullAWSAccess` is attached everywhere, which allows everything; you then add denies. ### How SCPs are inherited [#how-scps-are-inherited]
![SCP inheritance: Account A is limited by its own SCP and its OU's SCP; Account E has no extra limits](/diagrams/identity-scp-inheritance.light.svg) ![SCP inheritance: Account A is limited by its own SCP and its OU's SCP; Account E has no extra limits](/diagrams/identity-scp-inheritance.dark.svg)
Account A inherits every SCP above it.
- The **root** has `FullAWSAccess`, so nothing is blocked at the top. - **OU: Sandbox** adds an SCP that denies S3. Every account under it loses S3. - **Account A**, inside Sandbox, adds its own SCP that denies EC2. Its users can do **everything except S3 and EC2**, whatever their IAM policies say. - **OU: Workloads** and **Account E** add nothing, so Account E's users can do **everything their IAM policies allow**. - The **management account** is never limited by SCPs. ### Deny list or allow list [#deny-list-or-allow-list] - **Deny list** (the common way): keep `FullAWSAccess`, and add SCPs that deny specific things, such as `dynamodb:*` or leaving the organization. - **Allow list:** replace `FullAWSAccess` with an SCP that allows only named services, such as `ec2:*` and `cloudwatch:*`. Anything not listed is blocked. ```json title="Deny list: allow everything except DynamoDB" { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowsAllActions", "Effect": "Allow", "Action": "*", "Resource": "*" }, { "Sid": "DenyDynamoDB", "Effect": "Deny", "Action": "dynamodb:*", "Resource": "*" } ] } ``` Common SCPs: deny all Regions except approved ones, stop accounts leaving the organization, stop anyone turning off CloudTrail or GuardDuty, require encryption. ## Resource control policies (RCPs) [#resource-control-policies-rcps] **Resource control policies** are a newer organization policy type, not in the slides. Where SCPs cap what your **principals** can do, RCPs cap what can be done to your **resources** (in supported services such as S3, KMS, STS, SQS and Secrets Manager), whoever is calling. A common use: make sure no one outside your organization can ever access your S3 buckets, even if a bucket policy is misconfigured. Like SCPs, RCPs never grant permissions and don't apply to the management account. ## Tag policies and other policy types [#tag-policies-and-other-policy-types] **Tag policies** standardise tags across the organization: - You define tag keys and their allowed values, for example `CostCenter` with values `100` or `200`. - You can **enforce** them for chosen resource types, so non-compliant tagging operations are blocked. Resources with no tags at all aren't affected. - A report lists tagged and non-compliant resources, and EventBridge can alert on non-compliant tags. - They help with cost allocation tags and attribute-based access control. Organizations has other policy types too, such as **backup policies** (AWS Backup plans for every account), **AI services opt-out policies**, and several **declarative policies** that fix a service's settings across accounts (for example EC2). ## Limits [#limits] | Item | Value | | --- | --- | | Accounts per organization | 10 by default, can be raised | | OU nesting depth | 5 levels below the root | | SCPs attached per root, OU or account | 10 | | SCP size | 10,240 characters | | RCPs attached per root, OU or account | 5 | Older material, including many practice tests, gives the SCP size limit as 5,120 characters and at most 5 SCPs per target. AWS now allows 10,240 characters and 10 SCPs per target. ## Real-world examples [#real-world-examples] - **A retail company** has OUs for Security, Infrastructure, Workloads (with Prod and Dev under it) and Sandbox. An SCP on Sandbox denies expensive services and every Region except one. - **A regulated firm** uses an SCP at the root that denies all Regions outside the EU, so data can't be stored elsewhere even by an admin. - **A group of start-ups** shares one organization so their combined usage reaches cheaper S3 and data transfer tiers. ## Exam tips [#exam-tips] - **"Manage many accounts centrally", "one bill"** → AWS Organizations, consolidated billing. - **"Share Reserved Instance / Savings Plans discounts between accounts"** → consolidated billing in Organizations. - **"Prevent all users in member accounts, including admins, from using a service or Region"** → SCP. - **"The SCP denies it but the management account can still do it"** → SCPs don't apply to the management account. - **"Ensure only principals in our organization can access our resources"** → RCP, or `aws:PrincipalOrgID` in resource policies. - **"Enforce consistent tags"** → tag policies. SCPs **restrict**, IAM policies **grant**. A user in a member account needs both: an IAM policy that allows the action and SCPs (at every level) that don't block it. ## Common traps [#common-traps] - **"Attach an SCP to give a user permissions."** SCPs never grant. - **"An SCP will stop the management account's admins."** It won't. - **"An account can be in two organizations."** Only one at a time. - **"Tag policies tag resources for you."** They define and enforce rules; they don't add tags to untagged resources. ## Hands-on lab: create an organization and an SCP [#hands-on-lab-create-an-organization-and-an-scp] **Goal:** turn your lab account into a management account, build an OU structure and write an SCP. AWS Organizations has no charge. This lab creates no member accounts, so you can delete the organization afterwards. Don't create or invite member accounts in this lab. A new member account needs its own email address and must be closed separately, which takes time. Without member accounts, the organization can be deleted in one step. ### Create the organization [#create-the-organization] Open **AWS Organizations → Create an organization**. Your account becomes the management account. AWS emails you to verify the address. ### Build OUs [#build-ous] Under **AWS accounts**, select **Root → Actions → Create new** and create `Sandbox` and `Workloads`. Inside `Workloads`, create `Prod` and `Dev`. ### Turn on SCPs [#turn-on-scps] Open **Policies → Service control policies → Enable**. The `FullAWSAccess` policy is now attached to the root and every OU. ### Write an SCP [#write-an-scp] Choose **Create policy**, name it `deny-outside-us-east-1`, and paste: ```json { "Version": "2012-10-17", "Statement": [{ "Sid": "DenyOtherRegions", "Effect": "Deny", "NotAction": ["iam:*", "organizations:*", "sts:*", "support:*", "cloudfront:*", "route53:*"], "Resource": "*", "Condition": { "StringNotEquals": { "aws:RequestedRegion": "us-east-1" } } }] } ``` `NotAction` leaves global services out of the deny. Attach the policy to the `Sandbox` OU. It would block every member account in Sandbox from using other Regions; your management account isn't affected. **Expected result:** an organization with Sandbox and Workloads (Prod, Dev) OUs, and an SCP attached to Sandbox. **Clean up:** ### Delete the organization [#delete-the-organization] Detach and delete the SCP, delete the OUs, then open **Settings → Delete organization**. This works because the organization has no member accounts. ## AWS documentation [#aws-documentation] - [What is AWS Organizations?](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html) - [Consolidated billing for AWS Organizations](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/consolidated-billing.html) - [Service control policies (SCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) - [Example SCPs](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html) - [Resource control policies (RCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html) - [Tag policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) - [Quotas for AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) # Conditions and policy evaluation (/docs/identity/policy-conditions-evaluation) ## What it is [#what-it-is] Basic policies say *who* can do *what* on *which resource*. Real designs need more: - **[Conditions](/docs/glossary#term-iam-condition)** add *when*: only from the office IP range, only in two Regions, only with MFA, only on resources with a certain tag. - **[Permissions boundaries](/docs/glossary#term-permissions-boundary)** set the *most* an identity can ever be given, even by an admin who can write policies. - **Policy evaluation logic** is how AWS combines every policy that applies to a request into one answer: allow or deny. ## IAM conditions [#iam-conditions] A `Condition` block makes a statement apply only when its test is true. It uses an **operator** (such as `StringEquals`, `IpAddress`, `Bool`) and a **condition key** (such as `aws:SourceIp`). ### `aws:SourceIp`: where the call comes from [#awssourceip-where-the-call-comes-from] Restricts the IP address the API call is made **from**. This policy denies everything unless the call comes from two company IP ranges: ```json { "Effect": "Deny", "Action": "*", "Resource": "*", "Condition": { "NotIpAddress": { "aws:SourceIp": ["192.0.2.0/24", "203.0.113.0/24"] } } } ``` ### `aws:RequestedRegion`: which Region the call goes to [#awsrequestedregion-which-region-the-call-goes-to] Restricts the Region the API call is made **to**. This denies EC2, RDS and DynamoDB actions outside Frankfurt and Ireland: ```json { "Effect": "Deny", "Action": ["ec2:*", "rds:*", "dynamodb:*"], "Resource": "*", "Condition": { "StringNotEquals": { "aws:RequestedRegion": ["eu-central-1", "eu-west-1"] } } } ``` ### `ec2:ResourceTag` and `aws:PrincipalTag`: matching tags [#ec2resourcetag-and-awsprincipaltag-matching-tags] Allows starting and stopping only instances tagged `Project=DataAnalytics`, and only for users tagged `Department=Data`: ```json { "Effect": "Allow", "Action": ["ec2:StartInstances", "ec2:StopInstances"], "Resource": "arn:aws:ec2:us-east-1:123456789012:instance/*", "Condition": { "StringEquals": { "ec2:ResourceTag/Project": "DataAnalytics", "aws:PrincipalTag/Department": "Data" } } } ``` Using tags like this is called **attribute-based access control (ABAC)**: add a tag to a new resource or person and the permissions follow, with no policy change. ### `aws:MultiFactorAuthPresent`: require MFA [#awsmultifactorauthpresent-require-mfa] Allows all EC2 actions, but denies stopping and terminating instances unless the user signed in with MFA: ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ec2:*", "Resource": "*" }, { "Effect": "Deny", "Action": ["ec2:StopInstances", "ec2:TerminateInstances"], "Resource": "*", "Condition": { "BoolIfExists": { "aws:MultiFactorAuthPresent": false } } } ] } ``` The other examples on this page show a single statement; in a real policy each sits inside `"Statement": [ … ]` like this. ### `aws:PrincipalOrgID`: anyone in my organization [#awsprincipalorgid-anyone-in-my-organization] Used in **resource-based policies** to allow every account in an AWS organization at once, without listing each account ID. This bucket policy lets any member account read and write one folder, and blocks everyone outside the organization: ```json { "Effect": "Allow", "Principal": "*", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": "arn:aws:s3:::2022-financial-data/*", "Condition": { "StringEquals": { "aws:PrincipalOrgID": ["o-yyyyyyyyyy"] } } } ``` ## IAM for S3: bucket vs object [#iam-for-s3-bucket-vs-object] S3 permissions apply at two levels, and the `Resource` ARN must match: - **`s3:ListBucket`** is a **bucket-level** action. Its resource is the bucket: `arn:aws:s3:::test`. - **`s3:GetObject`, `s3:PutObject`, `s3:DeleteObject`** are **object-level** actions. Their resource is the objects: `arn:aws:s3:::test/*`. ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::test" }, { "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], "Resource": "arn:aws:s3:::test/*" } ] } ``` Writing `arn:aws:s3:::test` for `GetObject` (or `arn:aws:s3:::test/*` for `ListBucket`) silently grants nothing. ## Permissions boundaries [#permissions-boundaries] A permissions boundary is a managed policy attached to an **IAM user or role** (not a group) that sets the **maximum** permissions it can have. It never grants anything by itself.
![Effective permissions are where the SCP, the permissions boundary and the identity-based policy overlap](/diagrams/identity-effective-permissions.light.svg) ![Effective permissions are where the SCP, the permissions boundary and the identity-based policy overlap](/diagrams/identity-effective-permissions.dark.svg)
Effective permissions: what all three allow.
Three circles overlap: the organization's **SCPs and RCPs**, the **permissions boundary**, and the **identity-based policy**. An action is allowed only in the middle, where all three allow it. For example: the boundary allows `s3:*`, `cloudwatch:*` and `ec2:*`. The user's policy allows `iam:CreateUser`. Result: **no permissions at all**, because nothing is allowed by both. **Use cases:** - **Delegate safely.** Let a team lead create IAM users for their team, with a boundary so the new users can never get more than the team's limits. - **Stop privilege escalation.** Developers can write their own policies but can't make themselves administrators, because the boundary caps them. - **Limit one user or role,** where an SCP would restrict a whole account. ## Policy evaluation logic [#policy-evaluation-logic] When a request arrives, AWS gathers every policy that applies and decides. Three rules sum it up: 1. **By default, everything is denied** (an *implicit deny*). 2. **An explicit `Deny` in any policy always wins.** 3. Otherwise, the request needs an `Allow` from every policy type that applies.
![Simplified IAM policy evaluation steps from explicit deny to allow](/diagrams/identity-policy-evaluation.light.svg) ![Simplified IAM policy evaluation steps from explicit deny to allow](/diagrams/identity-policy-evaluation.dark.svg)
How AWS decides, simplified for one account.
The checks run in this order: 1. **Explicit deny?** If any policy denies the action, the answer is Deny. 2. **Organization policies:** if the account is in an organization, its **SCPs and RCPs** must allow the action, or it's denied. 3. **Resource-based policy:** if the resource has one (a bucket policy, for example) and it allows the caller, the request is allowed (*). 4. **Identity-based policy:** the user's or role's policies must allow it. 5. **Permissions boundary:** if one is set, it must allow it. 6. **Session policy:** if the caller passed one when assuming a role, it must allow it. 7. If everything that applies allows it, the answer is **Allow**. (*) Within one account, a resource-based policy that names the caller is enough on its own. **Across accounts, both sides must allow**: the caller's identity policy in its account, *and* the resource-based policy in the other account. ### Worked example [#worked-example] This policy is attached to a user: ```json { "Version": "2012-10-17", "Statement": [ { "Action": "sqs:*", "Effect": "Deny", "Resource": "*" }, { "Action": ["sqs:DeleteQueue"], "Effect": "Allow", "Resource": "*" } ] } ``` - **Can the user call `sqs:CreateQueue`?** No: the explicit deny on `sqs:*` matches. - **Can the user call `sqs:DeleteQueue`?** No: the explicit deny still wins over the allow. - **Can the user call `ec2:DescribeInstances`?** No: nothing allows it, so the implicit deny applies. ## Exam tips [#exam-tips] - **"Only allow API calls from the corporate network"** → condition `aws:SourceIp`. - **"Restrict which Regions can be used"** → `aws:RequestedRegion` (in an IAM policy or, across accounts, an SCP). - **"Allow every account in our organization to access the bucket"** → bucket policy with `aws:PrincipalOrgID`. - **"Let developers create roles without being able to escalate privileges"** → permissions boundary. - **"Policy allows and another denies"** → explicit deny wins. - **"`ListBucket` doesn't work but `GetObject` does"** → wrong resource ARN level (bucket vs `bucket/*`). ## Common traps [#common-traps] - **"A permissions boundary grants permissions."** It only limits. The identity still needs an allow from its own policy. - **"Permissions boundaries can be set on groups."** Only on users and roles. - **"An allow overrides a deny if it's more specific."** An explicit deny always wins. - **"Cross-account: a bucket policy allowing the other account is enough."** The caller's own identity policy must also allow the action. ## Hands-on lab: test policies with the IAM policy simulator [#hands-on-lab-test-policies-with-the-iam-policy-simulator] **Goal:** check the worked example and a Region condition without touching real resources. The IAM policy simulator only evaluates policies; nothing is created except a test policy, which is free. ### Create a test policy [#create-a-test-policy] Open **IAM → Policies → Create policy → JSON** and paste the worked example above. Name it `saa-sqs-test` and create it. ### Open the simulator [#open-the-simulator] Go to [policysim.aws.amazon.com](https://policysim.aws.amazon.com). In the left panel choose **Policies**, then select `saa-sqs-test` under customer managed policies. ### Run the three questions [#run-the-three-questions] Choose service **Amazon SQS**, tick `CreateQueue` and `DeleteQueue`, and **Run simulation**. Both show **denied**, with *explicit deny*. Add **Amazon EC2 → DescribeInstances**: **implicitly denied**. ### Try a condition [#try-a-condition] Edit the policy to add a statement allowing `ec2:DescribeInstances` with `"Condition": {"StringEquals": {"aws:RequestedRegion": "eu-west-1"}}`. In the simulator, set the context key `aws:RequestedRegion` to `eu-west-1` (allowed), then to `us-east-1` (denied). **Expected result:** the simulator confirms each answer and shows which statement decided it. **Clean up:** delete the `saa-sqs-test` policy. ## AWS documentation [#aws-documentation] - [IAM JSON policy elements: Condition](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) - [AWS global condition context keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html) - [Permissions boundaries for IAM entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) - [Policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) - [Test IAM policies with the IAM policy simulator](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html) # AWS RAM (/docs/identity/ram) AWS Resource Access Manager is on the exam's in-scope list. The slides only mention it when sharing a Transit Gateway, so this page is written from the AWS documentation. ## What it is [#what-it-is] [AWS Resource Access Manager](/docs/glossary#term-aws-ram) (RAM) lets you **share resources you own with other AWS accounts**: inside your organization, with specific OUs, with individual accounts, and for some resource types with IAM roles and users. It exists because many resources are expensive or awkward to duplicate. A company with 30 accounts doesn't want 30 transit gateways or 30 copies of the same DNS rules. With RAM, one account owns the resource and the others use it. RAM has **no extra charge**. The owner pays for the resource as usual. ## How it works [#how-it-works] 1. The **owner** creates a **resource share**, adds resources to it, and names the **principals** to share with (accounts, OUs, the whole organization). 2. Inside an organization with sharing turned on, the share works **straight away, with no invitation**. Outside the organization, each account must accept an invitation. 3. The **participants** see the shared resources in their own account and use them, within the limits of the resource type. ### What can be shared [#what-can-be-shared] Some of the resource types RAM can share: - **VPC subnets** (only within your organization) — the basis of *VPC sharing*. - **Transit gateways**, **prefix lists**, **IPAM pools**. - **Route 53 Resolver rules** — share forwarding rules for on-premises DNS once with every account. - **License Manager configurations**. - **Aurora DB clusters** — for [cloning](/docs/databases/backups-restore-cloning#aurora-database-cloning) across accounts. - **EC2 capacity reservations**, **dedicated hosts**, **placement groups**. - **AWS Network Firewall** policies, **AWS Backup** vaults, **EventBridge** event buses and more. ## VPC sharing [#vpc-sharing] The most tested use of RAM. A central networking account owns a VPC and shares some of its **subnets** with other accounts in the organization. - **Participants launch their own resources** (EC2 instances, RDS databases, Lambda functions) into the shared subnets. - Participants **can't see, change or delete** resources that belong to the owner or to other participants. - The **owner** manages the VPC itself: subnets, route tables, gateways, network ACLs. - Resources in the shared subnets talk to each other over private IPs, as in one VPC, without peering. *Why:* fewer VPCs to manage, less IP address space used, and one central team controls the network while app teams keep their own accounts and bills. ## Real-world examples [#real-world-examples] - **A networking team** owns one transit gateway and shares it through RAM with all 50 accounts, which attach their VPCs to it. - **A central DNS team** shares Route 53 Resolver rules that forward `corp.example.com` queries to on-premises DNS, so every account resolves internal names. ## Exam tips [#exam-tips] - **"Share subnets / a VPC with other accounts in the organization"** → VPC sharing with AWS RAM. - **"Share a transit gateway, Resolver rules or License Manager configurations across accounts"** → AWS RAM. - **"Avoid creating duplicate resources in every account"** → share them with RAM. ## Common traps [#common-traps] - **"Participants can modify the shared VPC's route tables."** Only the owner manages the VPC and subnets. - **"VPC subnets can be shared with any AWS account."** Only with accounts in the same organization. ## Check yourself [#check-yourself] Sharing needs at least two accounts, so instead of a lab: Create one transit gateway in the networking account and share it with the other accounts through AWS RAM. Each account attaches its VPC to the shared transit gateway. VPC sharing: the network account owns the VPC and shares subnets with the app accounts through RAM. App teams launch resources in the shared subnets. ## AWS documentation [#aws-documentation] - [What is AWS Resource Access Manager?](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html) - [Shareable AWS resources](https://docs.aws.amazon.com/ram/latest/userguide/shareable.html) - [Share your VPC subnets with other accounts](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-sharing.html) # Roles and STS (/docs/identity/roles-and-sts) ## What it is [#what-it-is] An [IAM role](/docs/glossary#term-iam-role) is an identity with permissions but **no password and no access keys**. Instead, someone or something *assumes* the role and receives **temporary credentials** that expire by themselves. The service that hands out those credentials is the [AWS Security Token Service](/docs/glossary#term-aws-sts) (STS). Roles exist because long-term credentials are risky. An access key works until someone deletes it, so a leaked key is dangerous for months. Temporary credentials last from 15 minutes to a few hours, then stop working on their own. Roles are used for: - **AWS services acting for you**, such as an EC2 instance reading from S3, or a Lambda function writing to DynamoDB. - **Cross-account access**, such as an admin in one account working in another. - **Federation**: people who sign in elsewhere (a company directory, Google, IAM Identity Center) and get AWS access through a role. ## How it works [#how-it-works]
![Assuming a role: the caller asks STS, the trust policy is checked, and temporary credentials come back](/diagrams/identity-assume-role.light.svg) ![Assuming a role: the caller asks STS, the trust policy is checked, and temporary credentials come back](/diagrams/identity-assume-role.dark.svg)
Assuming a role through AWS STS.
1. A user or application that already has credentials calls `sts:AssumeRole` for a role. 2. The role's **trust policy** says who may assume it. If the caller isn't listed, the request fails. 3. If the caller is trusted, STS returns temporary credentials: an access key ID, a secret access key and a **session token**, plus an expiry time. 4. The caller uses those credentials to call AWS. While they're used, the caller has **the role's permissions**, not its own. ### Two policies on every role [#two-policies-on-every-role] - **Trust policy:** *who* can assume the role. It's a resource-based policy on the role, with a `Principal`, such as an AWS service (`ec2.amazonaws.com`), another account, or a federated identity provider. - **Permissions policy:** *what* the role can do once assumed. Same JSON as any identity policy. ```json title="Trust policy that lets EC2 assume the role" { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } ``` ## Roles for AWS services [#roles-for-aws-services] The most common roles let a service act on your behalf: EC2 instance roles, Lambda execution roles, and roles CloudFormation uses to create resources.
![An EC2 instance gets rotating temporary credentials from its IAM role and uses them to call S3](/diagrams/identity-ec2-role.light.svg) ![An EC2 instance gets rotating temporary credentials from its IAM role and uses them to call S3](/diagrams/identity-ec2-role.dark.svg)
An IAM role for an EC2 instance.
The role is attached to the EC2 instance through an **[instance profile](/docs/glossary#term-instance-profile)**, a small container that holds one role (the console creates it for you). AWS delivers temporary credentials to the instance through the instance metadata service and rotates them before they expire. The AWS SDK and CLI on the instance find them automatically, so the code contains no keys at all. **Service-linked roles** are a special kind: created and owned by an AWS service (for example Auto Scaling or Organizations), with permissions the service defines. You can see them but not edit their permissions. ## STS operations [#sts-operations] - **`AssumeRole`:** assume a role in your account or another account. - **`AssumeRoleWithSAML`:** for users signed in through a SAML 2.0 identity provider (such as Active Directory Federation Services). - **`AssumeRoleWithWebIdentity`:** for users signed in with an OpenID Connect provider (Google, Facebook, GitHub Actions). For mobile apps, AWS recommends Cognito instead. - **`GetSessionToken`:** temporary credentials for an IAM user, usually to add MFA to CLI work. - **`GetFederationToken`:** temporary credentials for a federated user, through a custom broker. - **`GetCallerIdentity`:** shows who the current credentials belong to. ### How long credentials last [#how-long-credentials-last] - `AssumeRole` credentials last **1 hour by default**. You can ask for 15 minutes up to the role's **maximum session duration**, which you set between 1 and 12 hours. - **Role chaining** (using one role's credentials to assume another role) is limited to **1 hour**. - `GetSessionToken` and `GetFederationToken` last 12 hours by default, up to 36 hours. ## Cross-account roles and switching roles [#cross-account-roles-and-switching-roles] To let users in account A work in account B: 1. In account B, create a role whose **trust policy** names account A (or specific users or roles in it). 2. Attach a permissions policy to the role with what they may do in B. 3. In account A, give the users permission to call `sts:AssumeRole` on that role's ARN. In the console, users then choose **Switch role**, enter account B's ID and the role name, and work in B until they switch back. With the CLI, they add a profile with `role_arn` and `source_profile`. Remember: while a user is in the role, they **give up their own permissions**. The [roles vs resource-based policies](/docs/identity/roles-vs-resource-policies) page explains when that matters.
Beyond the exam: external IDs for third parties When you let a third-party company (a monitoring vendor, for example) assume a role in your account, add an **external ID** condition to the trust policy. The vendor passes this secret value when assuming the role. It stops another customer of the same vendor from tricking the vendor into accessing your account (the "confused deputy" problem).
## Real-world examples [#real-world-examples] - **A photo app on EC2** saves uploads to S3 using an instance role. No keys exist anywhere in the code or on the servers. - **A company with dev and prod accounts** lets its engineers sign in once in a central account and switch into a read-only role in prod, and an admin role in dev. - **GitHub Actions** deploys to AWS by assuming a role through OpenID Connect, so no AWS keys are stored in GitHub. ## Exam tips [#exam-tips] - **"Give an EC2 instance / Lambda function access to an AWS service"** → an IAM role (instance profile for EC2, execution role for Lambda). - **"Temporary credentials"** → AWS STS, usually `AssumeRole`. - **"Users in another account need access"** → a cross-account role with a trust policy naming that account. - **"Federated users from a corporate directory (SAML)"** → `AssumeRoleWithSAML`, or more simply IAM Identity Center. - **"Who can assume this role?"** → the trust policy. **"What can the role do?"** → the permissions policy. If an answer stores access keys anywhere (in code, user data, environment variables, S3), and another answer uses a role, the role is almost always right. ## Common traps [#common-traps] - **"Attach a policy to the EC2 instance."** You attach a *role* (via an instance profile); the policy goes on the role. - **"Roles have passwords or long-term keys."** They don't. Only temporary credentials. - **"When I assume a role I keep my own permissions too."** You get only the role's permissions for that session. - **"Role chaining can last 12 hours."** It's capped at 1 hour. ## Hands-on lab: switch into a read-only role [#hands-on-lab-switch-into-a-read-only-role] **Goal:** create a role your own account can assume, then switch into it in the console and with the CLI. IAM and STS have no charge. **Before you start:** sign in as your IAM admin user. Note your 12-digit account ID (top-right menu). ### Create the role [#create-the-role] Open **IAM → Roles → Create role**. Choose **AWS account → This account**. Attach the AWS managed policy `ReadOnlyAccess`. Name the role `saa-readonly` and create it. ### Read its trust policy [#read-its-trust-policy] Open the role → **Trust relationships**. The principal is `arn:aws:iam:::root`, which means "any identity in this account that has permission to assume the role". Your admin user has that permission through `AdministratorAccess`. ### Switch role in the console [#switch-role-in-the-console] Open the account menu → **Switch role**. Enter your account ID and `saa-readonly`, pick a colour, and switch. The top bar now shows the role. Try to create an S3 bucket: it's denied. Then choose **Switch back**. ### Assume it with the CLI [#assume-it-with-the-cli] ```bash aws sts assume-role \ --role-arn arn:aws:iam:::role/saa-readonly \ --role-session-name lab-test --duration-seconds 900 ``` The output holds `AccessKeyId`, `SecretAccessKey`, `SessionToken` and an `Expiration` 15 minutes from now. **Expected result:** inside the role you can read everything and change nothing, and the CLI credentials expire after 15 minutes. **Clean up:** delete the `saa-readonly` role. ## AWS documentation [#aws-documentation] - [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) - [Temporary security credentials in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) - [Compare AWS STS credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) - [Use an IAM role to grant permissions to applications on EC2](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html) - [Switch from a user to an IAM role (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html) # Roles vs resource-based policies (/docs/identity/roles-vs-resource-policies) ## What it is [#what-it-is] There are two ways to let a principal in one account use a resource in another: - **Assume a role** in the other account, and act with that role's permissions. - **Call the resource directly**, when the resource has a **[resource-based policy](/docs/glossary#term-resource-based-policy)** (such as an S3 bucket policy) that allows the caller. Both work. The difference is what happens to the caller's **own** permissions. ## How it works [#how-it-works]
![Reaching a bucket in Account B by assuming a role, or directly through a bucket policy](/diagrams/identity-cross-account.light.svg) ![Reaching a bucket in Account B by assuming a role, or directly through a bucket policy](/diagrams/identity-cross-account.dark.svg)
Cross-account access: a role (top) or a resource-based policy (bottom).
- **Top: assume a role.** A user in Account A assumes a role in Account B, then reaches the bucket with the role's permissions. While in the role, the user **gives up their Account A permissions**. - **Bottom: resource-based policy.** The bucket in Account B has a bucket policy that allows Account A. The user calls the bucket directly and **keeps their own permissions**. ### Why it matters [#why-it-matters] A user in Account A needs to scan a DynamoDB table in **Account A** and write the results to an S3 bucket in **Account B**. - With a role, they'd lose access to the DynamoDB table in A the moment they assumed the role in B. They'd have to switch back and forth. - With a bucket policy in B allowing them, they read from A and write to B in one go, with their own permissions. So when one task touches both accounts, a resource-based policy is simpler, **if the service supports one**. ### Which services have resource-based policies? [#which-services-have-resource-based-policies] Many, including: **S3 buckets**, **SNS topics**, **SQS queues**, **Lambda functions**, **KMS keys**, **API Gateway** APIs, **ECR repositories**, **Secrets Manager** secrets and **EventBridge** event buses. Services without them, such as EC2 or most of RDS's management actions, need a role. ## Example: EventBridge targets [#example-eventbridge-targets] When an EventBridge rule fires, it needs permission to act on its target. Which method it uses depends on the target: - **Targets with resource-based policies** (Lambda, SNS, SQS, S3, API Gateway): the target's policy allows EventBridge. For a Lambda function, a statement in the function's policy lets `events.amazonaws.com` invoke it. - **Targets without them** (EC2 Auto Scaling, Systems Manager Run Command, ECS tasks): EventBridge assumes an **IAM role** that has the permission. ## Compared side by side [#compared-side-by-side] **Assuming a role** - The caller **gives up** its own permissions for the session. - Works with **any service**. - Access is granted in the role's trust and permissions policies. - Across accounts, the caller needs permission to call `sts:AssumeRole`. **A resource-based policy** - The caller **keeps** its own permissions. - Works only with **services that support** resource-based policies. - Access is granted in the policy on the resource. - Across accounts, the caller's identity policy must also allow the action. ## Exam tips [#exam-tips] - **"Read from a resource in account A and write to a resource in account B at the same time"** → resource-based policy on the B resource. - **"Service doesn't support resource-based policies"** (EC2, for example) → cross-account role. - **"Allow EventBridge to invoke a Lambda function"** → Lambda resource-based policy. **"…to run an ECS task"** → IAM role for EventBridge. ## Common traps [#common-traps] - **"Assuming a role adds its permissions to mine."** It replaces them for the session. - **"Every service has resource-based policies."** Only some do. Check before choosing that option. ## Check yourself [#check-yourself] This topic needs two accounts to try for real, so instead of a lab: Add a bucket policy on B's bucket that allows the admin's principal (or account A) to `s3:PutObject`, and make sure the admin's identity policy in A allows it too. They keep their own permissions and can read from A and write to B together. A resource-based policy on the Lambda function that allows `events.amazonaws.com` (scoped to the rule's ARN). Lambda supports resource-based policies. A cross-account role in B with EC2 permissions, trusted by account A. EC2 has no resource-based policies. ## AWS documentation [#aws-documentation] - [Identity-based and resource-based policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_identity-vs-resource.html) - [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) - [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) - [Using resource-based policies for Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-resource-based.html) # Security tools and best practices (/docs/identity/security-tools-best-practices) ## What it is [#what-it-is] Over time, accounts collect unused users, old access keys and policies that give more than anyone needs. IAM has tools to find them: - The **[credential report](/docs/glossary#term-credential-report)** checks every user's credentials in the account. - **Last accessed information** (called *Access Advisor* in the course) shows which services an identity actually uses. - **[IAM Access Analyzer](/docs/glossary#term-iam-access-analyzer)** finds resources shared outside your account and permissions nobody uses, and helps you write least-privilege policies. ## Credential report [#credential-report] An account-level CSV file listing **every IAM user and the status of their credentials**: - whether the user has a console password, when it was last used and last changed; - whether MFA is active; - for each of the user's two access keys: active or not, when it was last rotated and last used, and in which Region and service. You can generate a new report **at most every four hours**; asking sooner returns the last one. Download it from **IAM → Credential report**. *Use it to find:* users without MFA, passwords never used, access keys older than 90 days. ## Last accessed information (Access Advisor) [#last-accessed-information-access-advisor] A user-, group-, role- or policy-level view that shows **which services an identity is allowed to use, and when it last tried to use each one**. AWS keeps at least 400 days of this data. Recent activity appears within about four hours, and it counts denied attempts too. *Use it to:* remove permissions for services an identity never uses. If a developer's role allows 40 services but they've touched three in a year, trim the policy to those three. ## IAM Access Analyzer [#iam-access-analyzer] Access Analyzer checks your permissions in a few ways: - **External access analyzer:** finds resources (S3 buckets, KMS keys, IAM roles, SQS queues, Lambda functions and more) that can be reached from **outside your zone of trust**, meaning your account or your organization. Free. - **Unused access analyzer:** finds unused roles, unused access keys and passwords, and unused services and actions in policies. Paid per IAM role or user analyzed each month. - **Internal access analyzer:** shows who inside your organization can reach selected critical resources. - **Policy validation:** checks a policy you're writing for errors and risky patterns, such as `"Action": "*"` with `"Resource": "*"`. - **Policy generation:** builds a least-privilege policy from the actions a role really used, read from CloudTrail logs. ## IAM best practices [#iam-best-practices] The course's list, updated with AWS's current advice: - **Don't use the root user** except for the tasks that need it. - **One person, one identity.** Never share users or access keys. - **Prefer IAM Identity Center** (with temporary credentials) for people, especially across several accounts. Use IAM users only where you must. - **Put users in groups** and attach permissions to groups, not to individual users. - **Set a strong password policy** and **require MFA** for every human. - **Use roles** for AWS services and applications, never access keys. - **Use access keys only when nothing else works**, and rotate them. - **Grant least privilege**, and audit with the credential report, last accessed data and Access Analyzer. The slides recommend "access keys for programmatic access (CLI / SDK)". AWS now recommends short-term credentials instead: IAM Identity Center or `aws login` for people, and roles for workloads. IAM Access Analyzer also isn't in the slides, but it's the main IAM auditing tool today. ## Exam tips [#exam-tips] - **"List all users and the status of their passwords, MFA and access keys"** → IAM credential report. - **"See which services a user / role has used, to remove unused permissions"** → last accessed information (Access Advisor). - **"Find S3 buckets or roles shared with external accounts"** → IAM Access Analyzer. - **"Generate a least-privilege policy based on actual activity"** → Access Analyzer policy generation. ## Common traps [#common-traps] - **Mixing up the two old tools.** The credential report is **account-level** (all users, their credentials). Access Advisor is **identity-level** (one identity, its service usage). - **"The credential report shows what users did."** It shows credential status. For actions, use CloudTrail. ## Hands-on lab: audit your account [#hands-on-lab-audit-your-account] **Goal:** generate a credential report, check last accessed data, and turn on an external access analyzer. The credential report, last accessed data and the external access analyzer have no charge. Don't create an *unused access* analyzer: that one is billed. ### Download the credential report [#download-the-credential-report] Open **IAM → Credential report → Download credentials report** and open the CSV. Check that `mfa_active` is `true` for the root user (``) and your admin user. ### Check last accessed data [#check-last-accessed-data] Open **IAM → Users → your user → Last accessed**. You'll see the services you've touched in the labs so far, and *Not accessed in the tracking period* for the rest. ### Create an external access analyzer [#create-an-external-access-analyzer] Open **IAM → Access analyzer → Analyzer settings → Create analyzer**. Choose **External access analysis**, zone of trust **Current account**, and create it in `us-east-1`. After a few minutes, open **Findings**. A new lab account usually has none. **Expected result:** a CSV showing every user's credentials, a list of services you've used, and an analyzer with no (or few) findings. **Clean up:** delete the analyzer if you don't want to keep it (**Analyzer settings → select → Delete**). It's free either way. ## AWS documentation [#aws-documentation] - [Generate credential reports for your AWS account](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html) - [Refine permissions using last accessed information](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_last-accessed.html) - [What is IAM Access Analyzer?](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) - [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) # Users, groups and policies (/docs/identity/users-groups-policies) ## What it is [#what-it-is] An [IAM user](/docs/glossary#term-iam-user) is an identity for one person (or, rarely, one application) in your AWS account. An [IAM group](/docs/glossary#term-iam-group) is a set of users who need the same permissions. An [IAM policy](/docs/glossary#term-iam-policy) is a JSON document that lists what's allowed or denied. Together they solve a simple problem: everyone who uses the account needs their own sign-in, and you need an easy way to give the right access to the right people. ## How it works [#how-it-works]
![IAM users in the Developers, Operations and Audit Team groups, with Fred in no group](/diagrams/identity-users-groups.light.svg) ![IAM users in the Developers, Operations and Audit Team groups, with Fred in no group](/diagrams/identity-users-groups.dark.svg)
Users, groups and where their permissions come from.
One AWS account holds six users and three groups: - **Alice and Bob** are in *Developers*, so they get the Developers group's policies. - **Charles** is in *Developers* and *Audit Team*. He gets the policies of **both** groups. - **David** is in *Operations* and *Audit Team*, so he also gets both sets. - **Edward** is only in *Operations*. - **Fred** is in no group. His permissions come from an *inline policy* attached directly to his user. The rules behind the picture: - A user can be in **no group, one group or several groups**. Permissions from every group add up. - A group contains **only users**. Groups can't contain other groups. - A policy can be attached to a **user**, a **group** or a **role**. Attaching to groups is easier to manage than attaching to each user. - IAM is **global**: users, groups and policies exist once for the whole account, not per Region. ## Policies [#policies] A policy is a JSON document. This one lets its holder read and write objects in one S3 bucket: ```json title="S3 read and write policy" { "Version": "2012-10-17", "Id": "S3-Account-Permissions", "Statement": [ { "Sid": "AllowReadWriteOnMyBucket", "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": ["arn:aws:s3:::my-bucket/*"] } ] } ``` ### The parts of a policy [#the-parts-of-a-policy] - **`Version`**: the policy language version. Always use `"2012-10-17"`. - **`Id`** (optional): a name for the policy. - **`Statement`**: one or more statements. Each statement has: - **`Sid`** (optional): a name for the statement. - **`Effect`**: `Allow` or `Deny`. - **`Principal`**: who the statement applies to. Used only in *resource-based* policies (such as an S3 bucket policy), because an identity policy already applies to whoever it's attached to. - **`Action`**: the API actions, such as `s3:GetObject` or `ec2:*`. - **`Resource`**: what the actions apply to, written as [ARNs](/docs/glossary#term-arn). - **`Condition`** (optional): when the statement applies, for example only from one IP range. See [conditions](/docs/identity/policy-conditions-evaluation#iam-conditions). An **ARN** (Amazon Resource Name) is the unique name of a resource: `arn:aws:s3:::my-bucket` is a bucket, `arn:aws:s3:::my-bucket/*` is every object in it, and `arn:aws:iam::123456789012:user/alice` is a user. `*` is a wildcard: `"Action": "ec2:Describe*"` matches every EC2 action that starts with `Describe`. ### Kinds of policies [#kinds-of-policies] - **AWS managed policies** are written and updated by AWS for common jobs, such as `AdministratorAccess`, `ReadOnlyAccess` or `AmazonS3ReadOnlyAccess`. Quick to use, but often broader than you need. - **Customer managed policies** are ones you write. You can attach one to many users, groups and roles, and change it in one place. - **[Inline policies](/docs/glossary#term-inline-policy)** are written inside one user, group or role and deleted with it. Use them only for a strict one-to-one link. ### Least privilege [#least-privilege] The [principle of least privilege](/docs/glossary#term-least-privilege) means giving each identity only the permissions it needs for its job, and nothing more. If its credentials leak, the damage is limited to what it could do. In practice: start from an AWS managed policy to get going, then replace it with a customer managed policy that lists only the actions and resources really used. [IAM Access Analyzer](/docs/identity/security-tools-best-practices#iam-access-analyzer) can generate such a policy from the activity in CloudTrail. ## Limits [#limits] | Item | Default | Can be raised to | | --- | --- | --- | | Groups per account | 300 | 500 | | Customer managed policies per account | 1,500 | 10,000 | | Managed policies per user | 10 | 20 | | Managed policies per group | 10 | 10 | | Size of one managed policy | 6,144 characters | fixed | ## Real-world examples [#real-world-examples] - **A start-up** creates an *Admins* group with `AdministratorAccess` for its two founders, and a *Developers* group with a custom policy for everyone else. New hires are added to *Developers* on day one. - **An auditor** is given a user in an *Audit* group with `SecurityAudit` and `ReadOnlyAccess`. They can see everything and change nothing. ## Exam tips [#exam-tips] - **"Give a team the same permissions"** → put the users in a **group** and attach the policy to the group. - **"Least privilege"** → a customer managed policy with only the needed actions and resources. - **"Policy attached directly to one user and deleted with it"** → inline policy. - **"Can a group contain another group?"** → no. - **`"Principal"` in a policy** → it's a resource-based policy (for example a bucket policy), not an identity policy. Be ready to read a short policy and say what it allows. Check the `Effect`, the `Action` list and the `Resource` ARN. A bucket ARN (`arn:aws:s3:::my-bucket`) and an object ARN (`arn:aws:s3:::my-bucket/*`) are different resources. ## Common traps [#common-traps] - **"Attach `AdministratorAccess` so the developer isn't blocked."** It breaks least privilege. Give the specific permissions instead. - **Thinking IAM users are per Region.** IAM is global. - **Sharing one IAM user between people.** One person, one user, so every action is traceable to someone. ## Hands-on lab: create an admin user and group [#hands-on-lab-create-an-admin-user-and-group] **Goal:** stop using the root user. Create an *Admins* group, a personal IAM user in it, and sign in as that user. IAM has no charge. **Before you start:** sign in as the root user (the email you signed up with). This is one of the few times you should. ### Create the group [#create-the-group] Open **IAM → User groups → Create group**. Name it `Admins` and attach the AWS managed policy `AdministratorAccess`. Choose **Create user group**. ### Create your user [#create-your-user] Open **IAM → Users → Create user**. Name it after yourself, for example `alex`. Tick **Provide user access to the AWS Management Console**, choose **I want to create an IAM user**, set a custom password and untick *must create a new password at next sign-in*. ### Add the user to the group [#add-the-user-to-the-group] On the permissions step choose **Add user to group**, tick `Admins`, then create the user. Open the user and check that the **Permissions** tab shows `AdministratorAccess` *attached via group Admins*. ### Set an account alias [#set-an-account-alias] On the **IAM dashboard**, under **AWS Account**, choose **Create** next to *Account alias* and enter something unique, such as `alex-saa-lab`. Your sign-in URL becomes `https://alex-saa-lab.signin.aws.amazon.com/console`. ### Sign in as the new user [#sign-in-as-the-new-user] Open the sign-in URL in a private browser window and sign in as `alex`. The top-right corner now shows `alex @ alex-saa-lab`. **Expected result:** you can do everything in the console as your IAM user. Use it for every later lab, and add MFA to it in the [next lab](/docs/identity/mfa-password-policy#hands-on-lab-protect-your-sign-ins). **Clean up:** keep this user and group for the rest of the course. ## AWS documentation [#aws-documentation] - [IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) - [IAM user groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) - [Policies and permissions in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) - [IAM JSON policy element reference](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html) - [IAM and AWS STS quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) # Welcome (/docs) This handbook covers everything you need for the **AWS Certified Solutions Architect – Associate (SAA-C03)** exam, from first principles to the tricky edge cases. It follows the structure of Stephane Maarek's SAA course, checks every fact against the AWS documentation, and adds the exam-guide topics the course leaves out. The goal is understanding, not memorising. Each page explains what a service is, why it exists and how it works, and only then turns to exam tips. ## How the notes are organised [#how-the-notes-are-organised] The sidebar groups services by **family**: Compute, Storage, Databases, Networking, Security and so on. Inside each group, pages follow the course order. The groups are also ordered so you can read them top to bottom as a course. When a page needs an idea from a later group, it explains the minimum on the spot and links forward. ## How a page is laid out [#how-a-page-is-laid-out] Most pages use the same sections, in this order. A page skips a section when it doesn't fit. 1. **What it is**: the service in plain English, and the problem it solves. 2. **How it works**: a diagram with a short caption, then a written walk-through of the diagram. 3. **Key features**: one section per feature or option. 4. **Limits and pricing**: the numbers that matter, checked against AWS docs, and how you are billed. 5. **Real-world examples**: how real companies use it. 6. **Compared with…**: a comparison diagram or a short table, when similar options exist. 7. **Exam tips**: words you'll see in questions and the answer they point to. 8. **Common traps**: wrong answers that look right, and why they are wrong. 9. **Hands-on lab**: steps, expected result, clean-up and a cost warning. 10. **AWS documentation**: links to every AWS page used. Every diagram is followed by a written walk-through, so the page still makes sense without the picture. Click or tap a diagram to zoom in. ## The boxes you'll see [#the-boxes-youll-see] Each kind of box looks the same on every page, so you can spot it at a glance. How a topic shows up in exam questions: keywords, and the answer they point to. A wrong answer that looks right, and why it is wrong. A concrete scenario that shows the idea in use. Something that has changed since the course slides were made. The notes follow the current AWS documentation. A service the course covers but the current exam guide doesn't list. It's here for completeness: read it once, don't drill it. A lab step that creates billable resources, with a rough cost. Material that's useful at work but not tested sits in a collapsed block. Skip these on exam review:
Beyond the exam: what these blocks look like Extra depth goes here: how a feature works inside, production advice, or newer options the exam doesn't ask about yet.
## Labs and your AWS bill [#labs-and-your-aws-bill] Every topic has a hands-on lab. The labs assume your account **has no Free Tier left**, so they are written to cost as little as possible: - Each lab starts with a **Costs money** box: what you'll pay for, and roughly how much. - Labs use the smallest sizes and the **us-east-1** (N. Virginia) Region, which is usually the cheapest. Any Region works if you prefer another one. - Every resource gets the tag `Project=saa-lab`, so you can find leftovers in one search. - Every lab ends with clean-up steps. Do them straight away: most lab costs come from resources left running overnight. Do the lab below before any other. It's free, and it emails you before a forgotten resource turns into a big bill. ## Hands-on lab: set a budget alert [#hands-on-lab-set-a-budget-alert] **Goal:** get an email when your AWS spend for the month passes an amount you choose. AWS Budgets doesn't charge for budgets that only monitor and send notifications. Only budgets that take automatic actions, beyond the first two, or that email scheduled reports, cost money. **Before you start:** sign in to the AWS Management Console as a user who can see billing. The root user can. An IAM user needs billing access turned on (covered in the Identity & Access group). ### Open AWS Budgets [#open-aws-budgets] In the search bar at the top of the console, type **Budgets** and open **[AWS Budgets](/docs/cost/budgets-cur-tags#aws-budgets)** (part of Billing and Cost Management). Choose **Create budget**. ### Pick the monthly cost template [#pick-the-monthly-cost-template] Choose **Use a template (simplified)**, then **Monthly cost budget**. The *Zero spend budget* template is meant for accounts still on the Free Tier, which isn't you. ### Set the amount and the email [#set-the-amount-and-the-email] - **Budget name:** `saa-lab-monthly` - **Enter your budgeted amount:** what you're willing to spend on labs per month, for example `20` USD. - **Email recipients:** your email address. The template alerts you when actual spend passes 85% and 100% of the amount, and when the forecast for the month is going to pass 100%. ### Create it [#create-it] Choose **Create budget**. The budget appears in the list with its current spend. **Expected result:** the budget shows in the AWS Budgets list. Spend data can take up to a day to appear. When spend crosses a threshold, you get an email from AWS Budgets. **Clean up:** nothing to clean up. Keep this budget for the whole course. ## AWS documentation [#aws-documentation] - [AWS Certified Solutions Architect – Associate (SAA-C03) exam guide](https://docs.aws.amazon.com/aws-certification/latest/solutions-architect-associate-03/solutions-architect-associate-03.html) - [Using budget templates](https://docs.aws.amazon.com/cost-management/latest/userguide/budget-templates.html) - [AWS Budgets pricing](https://aws.amazon.com/aws-cost-management/aws-budgets/pricing/) # Amazon MQ (/docs/integration/amazon-mq) ## What it is [#what-it-is] SQS and SNS are **cloud-native** services that use AWS's own APIs. Traditional applications running on premises often use **open messaging protocols** instead: **MQTT, AMQP, STOMP, OpenWire, WSS** (WebSocket), through message brokers such as Apache ActiveMQ or RabbitMQ. When **migrating** such an application to the cloud, rewriting it to use SQS and SNS takes time. Instead, you can use **[Amazon MQ](/docs/glossary#term-amazon-mq)**: a **managed message broker** service for **RabbitMQ** and **Apache ActiveMQ**. Your applications keep their existing protocols and code; AWS runs the brokers. - Amazon MQ has both **queue** features (like SQS) and **topic** features (like SNS). - It **doesn't scale** as much as SQS and SNS. - It **runs on servers** (brokers you size), and can run **Multi-AZ with failover**. ## High availability [#high-availability]
![Amazon MQ high availability for ActiveMQ: a client connects to the active broker in one Availability Zone, with a standby broker in another; both use shared Amazon EFS storage, and on failure the client fails over to the standby](/diagrams/integration-amazon-mq.light.svg) ![Amazon MQ high availability for ActiveMQ: a client connects to the active broker in one Availability Zone, with a standby broker in another; both use shared Amazon EFS storage, and on failure the client fails over to the standby](/diagrams/integration-amazon-mq.dark.svg)
An active and a standby broker sharing storage.
- **ActiveMQ:** an **active/standby** deployment runs one broker in each of **two AZs**, sharing **Amazon EFS** storage. Clients connect to the active broker; if it fails, the standby takes over with the same data, and clients **fail over** to it. - **RabbitMQ:** a **cluster** deployment runs **three broker nodes** in three AZs behind a Network Load Balancer, with queues replicated across them. ## Real-world examples [#real-world-examples] - **A bank** moves a Java app that uses JMS over ActiveMQ to AWS. With Amazon MQ, the code doesn't change; only the broker URL does. - **A logistics company** keeps using RabbitMQ and AMQP for its warehouse systems, but stops patching broker servers itself. ## Exam tips [#exam-tips] - **"Migrate an on-premises app using MQTT, AMQP, STOMP, OpenWire or JMS without changing code"** → Amazon MQ. - **"ActiveMQ or RabbitMQ in the cloud, managed"** → Amazon MQ. - **"New cloud-native application, massive scale"** → SQS / SNS rather than Amazon MQ. - **"High availability for Amazon MQ"** → active/standby across two AZs (ActiveMQ) or a three-node cluster (RabbitMQ). ## Common traps [#common-traps] - **"Amazon MQ scales like SQS."** It runs on brokers you size; SQS scales without limit. - **"Rewrite the legacy app to use SQS to move to AWS."** Possible, but Amazon MQ avoids the rewrite. ## Check yourself [#check-yourself] A broker runs by the hour (about $0.03 an hour for the smallest single-instance ActiveMQ broker, double for active/standby), so instead of a lab: Amazon MQ for RabbitMQ: the app keeps using AMQP; AWS runs and maintains the brokers. A cluster deployment gives high availability. Amazon SQS: cloud-native, serverless and virtually unlimited. Amazon MQ is for apps that already depend on broker protocols. ## AWS documentation [#aws-documentation] - [What is Amazon MQ?](https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/welcome.html) - [Deployment options for Amazon MQ for ActiveMQ brokers](https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/active-standby-broker-deployment.html) - [Deployment options for Amazon MQ for RabbitMQ brokers](https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/rabbitmq-broker-architecture.html) # Amazon AppFlow (/docs/integration/appflow) ## What it is [#what-it-is] **[Amazon AppFlow](/docs/glossary#term-amazon-appflow)** is a fully managed integration service that **securely transfers data between Software-as-a-Service (SaaS) applications and AWS**, without writing integration code.
![Amazon AppFlow: data from SaaS sources such as Salesforce, SAP, Zendesk, Slack and ServiceNow flows through AppFlow, which can filter and validate it, into destinations such as Amazon S3, Redshift, Snowflake or Salesforce; flows run on a schedule, on an event or on demand, optionally over PrivateLink](/diagrams/integration-appflow.light.svg) ![Amazon AppFlow: data from SaaS sources such as Salesforce, SAP, Zendesk, Slack and ServiceNow flows through AppFlow, which can filter and validate it, into destinations such as Amazon S3, Redshift, Snowflake or Salesforce; flows run on a schedule, on an event or on demand, optionally over PrivateLink](/diagrams/integration-appflow.dark.svg)
SaaS data into AWS, with no code.
- **Sources:** Salesforce, SAP, Zendesk, Slack, ServiceNow and many more. - **Destinations:** AWS services like **Amazon S3** and **Amazon Redshift**, or non-AWS ones such as **Snowflake** and **Salesforce**. - **Frequency:** on a **schedule**, in response to **events**, or **on demand**. - **Data transformation:** filtering and validation. - **Encrypted** over the public internet, or sent privately over **AWS PrivateLink**. - You don't spend time writing integrations: use the SaaS APIs straight away. Data written to S3 can be catalogued in the Glue Data Catalog. ## Real-world examples [#real-world-examples] - **A sales team** syncs new Salesforce opportunities into Redshift every hour for dashboards. - **A support team** exports Zendesk tickets to S3 each night to analyse them with Athena. ## Exam tips [#exam-tips] - **"Transfer data from Salesforce (or another SaaS app) to S3 or Redshift with no code"** → Amazon AppFlow. - **"SaaS data transfer that must not cross the public internet"** → AppFlow with PrivateLink. ## Common traps [#common-traps] - **"Write a Lambda function to call the Salesforce API on a schedule."** It works, but AppFlow does it without code. - **"AppFlow moves data between AWS services."** It's for SaaS applications and AWS. ## Check yourself [#check-yourself] AppFlow needs an account with a SaaS application to connect, so instead of a lab: Amazon AppFlow with Salesforce as the source and S3 as the destination, on a daily schedule. ## AWS documentation [#aws-documentation] - [What is Amazon AppFlow?](https://docs.aws.amazon.com/appflow/latest/userguide/what-is-appflow.html) # Amazon EventBridge (/docs/integration/eventbridge) ## What it is [#what-it-is] **[Amazon EventBridge](/docs/glossary#term-amazon-eventbridge)** (formerly *CloudWatch Events*) is a serverless **event router**. Things happen in AWS and in your applications ("an instance stopped", "a file was uploaded", "an order was placed"); EventBridge receives those **events** and sends them to the services that should react. Two basic uses: - **Schedules:** cron jobs (scheduled scripts), for example run a Lambda function **every hour**. - **Event patterns:** rules that react to a service doing something, for example **when the root user signs in**, send a message to an **SNS topic** that emails the security team. Targets include triggering Lambda functions and sending SQS or SNS messages, among many others. ## Rules [#rules]
![EventBridge rules: events from sources such as an EC2 state change, an S3 object created, a CloudTrail API call, a schedule or SaaS partners arrive on an event bus; a rule with an event pattern matches them and sends them to targets such as Lambda, SQS, SNS, Step Functions, Kinesis, an ECS task, Batch or Systems Manager](/diagrams/integration-eventbridge-rules.light.svg) ![EventBridge rules: events from sources such as an EC2 state change, an S3 object created, a CloudTrail API call, a schedule or SaaS partners arrive on an event bus; a rule with an event pattern matches them and sends them to targets such as Lambda, SQS, SNS, Step Functions, Kinesis, an ECS task, Batch or Systems Manager](/diagrams/integration-eventbridge-rules.dark.svg)
Events in, a matching rule, targets out.
1. A **source** produces an event, a small JSON document. Examples: an **EC2 instance** starts or stops; **CodeBuild** reports a failed build; **S3** has a new object; **Trusted Advisor** has a new finding; **CloudTrail** records any API call; or a **schedule** fires (for example every 4 hours). 2. A **rule** on the event bus matches events with an **event pattern** (a filter on the event's fields). 3. EventBridge sends matching events to the rule's **targets** (up to five per rule): - **compute:** Lambda, AWS Batch, ECS tasks; - **integration:** SQS, SNS, Kinesis Data Streams; - **orchestration:** Step Functions, CodePipeline, CodeBuild; - **maintenance:** Systems Manager, EC2 actions. For schedules, AWS now recommends **EventBridge Scheduler**: it handles millions of schedules, one-time or recurring (cron and rate), with time zones and retries, and can call over 270 AWS services directly. ## Event buses [#event-buses]
![Three kinds of EventBridge event bus: the default bus receives events from AWS services; partner buses receive events from SaaS partners such as Zendesk and Datadog; custom buses receive events from your applications through the PutEvents API; buses support archive and replay, a schema registry and resource-based policies for cross-account access](/diagrams/integration-eventbridge-buses.light.svg) ![Three kinds of EventBridge event bus: the default bus receives events from AWS services; partner buses receive events from SaaS partners such as Zendesk and Datadog; custom buses receive events from your applications through the PutEvents API; buses support archive and replay, a schema registry and resource-based policies for cross-account access](/diagrams/integration-eventbridge-buses.dark.svg)
One bus for AWS, one per SaaS partner, and your own.
- **Default event bus:** events from **AWS services**. - **Partner event bus:** events from **SaaS partners**, such as Zendesk, Datadog or Auth0. - **Custom event bus:** events from **your own applications**, sent with the `PutEvents` API. Other features: - **Resource-based policies:** event buses can be used by **other AWS accounts**. - **Archive** events (all or filtered) sent to a bus, **indefinitely or for a set period**, and **replay** archived events, for example after fixing a bug in a consumer. - **Schema registry:** EventBridge can **analyse the events** on your bus and **infer their schema**. You can then **generate code** for your application that knows in advance how the event data is structured. Schemas are **versioned**. - **EventBridge Pipes:** point-to-point integrations from one source (such as an SQS queue or a DynamoDB stream) to one target, with optional filtering and enrichment. AWS now offers a new **Custom Event Bus** that delivers events to **subscribers** created by consumers, keeps events for a period you set, and supports ordered delivery and replay. The rules-and-targets buses described above are now called **Custom Event Bus - Classic**, and remain available. This change is newer than the exam material; the rules model is what questions use. ## Resource-based policies [#resource-based-policies] A resource-based policy manages permissions for a specific event bus: for example, **allow or deny events from another AWS account or Region**. **Use case:** aggregate all events from your **AWS Organization** into **one central account** or Region. The central bus's policy allows `events:PutEvents` from the other accounts (or the whole organization), and each account forwards its events there. ## Intercepting API calls [#intercepting-api-calls]
![Intercepting API calls: a user calls DynamoDB DeleteTable; CloudTrail logs the API call; an EventBridge rule matching that event sends an alert through Amazon SNS to the team](/diagrams/integration-eventbridge-cloudtrail.light.svg) ![Intercepting API calls: a user calls DynamoDB DeleteTable; CloudTrail logs the API call; an EventBridge rule matching that event sends an alert through Amazon SNS to the team](/diagrams/integration-eventbridge-cloudtrail.dark.svg)
Any API call can become an alert.
**CloudTrail** records API calls and sends them to EventBridge as events, so a rule can react to **any API call** in your account: - a user calls DynamoDB **`DeleteTable`** → alert through SNS; - a user calls **`AssumeRole`** on an IAM role → alert; - a user edits security group inbound rules (**`AuthorizeSecurityGroupIngress`**) → alert. CloudTrail is covered in the Monitoring & Governance group. ## Real-world examples [#real-world-examples] - **A nightly report** runs as a Lambda function on an EventBridge schedule at 02:00 UTC. - **A security team** gets an SNS alert within seconds whenever someone opens port 22 to the internet, through CloudTrail and an EventBridge rule. - **A support team** routes new Zendesk tickets from a partner event bus to a Lambda function that classifies them. - **A company with 40 accounts** forwards all GuardDuty findings to a central security account's event bus. ## Exam tips [#exam-tips] - **"Run a function on a schedule", "cron in AWS"** → EventBridge schedule (or EventBridge Scheduler). - **"React when an EC2 instance stops", "when an S3 object is created"** → EventBridge rule. - **"Alert when someone calls a specific API"** → CloudTrail + EventBridge rule + SNS. - **"Receive events from a SaaS application"** → partner event bus. - **"Centralize events from all accounts"** → event bus resource-based policy (allow the organization). - **"Reprocess past events after a bug fix"** → archive and replay. - **"Generate code bindings for event structures"** → schema registry. ## Common traps [#common-traps] - **"Use SNS to react to an EC2 state change."** The event comes through EventBridge; SNS can be the target. - **"EventBridge needs a running server for cron jobs."** Schedules are serverless. ## Hands-on lab: a scheduled rule and an event rule [#hands-on-lab-a-scheduled-rule-and-an-event-rule] **Goal:** send an email whenever an EC2 instance changes state. EventBridge rules on AWS service events are free; SNS email is free for 1,000 messages a month. Starting and stopping a `t3.micro` for a minute costs **under a cent**. Any Region works. **Before you start:** have an SNS topic with a confirmed email subscription, as in the [SNS lab](/docs/integration/sns#hands-on-lab-an-email-notification). ### Create the rule [#create-the-rule] **EventBridge → Rules → Create rule**. Name `saa-ec2-state`, event bus **default**, rule type **Rule with an event pattern**. Event source **AWS services → EC2 → EC2 Instance State-change Notification**, any state. Target **SNS topic** → your topic. Create. ### Trigger it [#trigger-it] Stop (or start) any EC2 instance, such as `saa-web`. Within a minute you receive an email containing the event JSON, with the instance ID and the new state. **Expected result:** an email for every EC2 state change, without writing code. **Clean up:** delete the `saa-ec2-state` rule (and the SNS topic if you no longer need it). ## AWS documentation [#aws-documentation] - [What is Amazon EventBridge?](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) - [Amazon EventBridge event buses](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-bus.html) - [Archiving and replaying events](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-archive.html) - [Amazon EventBridge schema registry](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-schema-registry.html) - [Sending and receiving events between AWS accounts](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-cross-account.html) - [Amazon EventBridge Pipes](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-pipes.html) - [What is Amazon EventBridge Scheduler?](https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html) # Application Integration (/docs/integration) ## What it is [#what-it-is] As soon as you run more than one application, they need to talk to each other. A web shop's **buying service** has to tell the **shipping service** about each new order. There are two ways to do it.
![Synchronous versus asynchronous communication: with synchronous calls the buying service calls the shipping service directly, so the shipping service must keep up; with asynchronous messaging the buying service sends work to a queue and moves on, and the shipping service processes it at its own pace](/diagrams/integration-sync-async.light.svg) ![Synchronous versus asynchronous communication: with synchronous calls the buying service calls the shipping service directly, so the shipping service must keep up; with asynchronous messaging the buying service sends work to a queue and moves on, and the shipping service processes it at its own pace](/diagrams/integration-sync-async.dark.svg)
Calling directly, or leaving the work in a queue.
- **Synchronous** (application to application): the buying service calls the shipping service and waits. Simple, but if shipping is slow or down, buying is too. Sudden spikes are a problem: what if you suddenly have to encode 1,000 videos when you usually encode 10? - **Asynchronous** or event-based (application to queue to application): the buying service drops a message in a queue and carries on; the shipping service picks it up when it can. The second way **[decouples](/docs/glossary#term-decoupling)** the applications: each one can scale, fail and be updated on its own. AWS offers three models for it: - **SQS**, the **queue** model; - **SNS**, the **pub/sub** (publish/subscribe) model; - **Kinesis**, the **real-time streaming** model. These services scale independently from your application. The group also covers **Amazon MQ** (for apps using standard broker protocols), **EventBridge** (event routing), **Step Functions** (workflows), **AppFlow** (SaaS data transfer) and the email and messaging services **SES** and **Pinpoint**. A video site lets users upload videos. The web tier saves each upload to S3 and puts a message in an **SQS** queue. A fleet of EC2 workers encodes videos from the queue, scaling with its length. When a video is ready, an **SNS** topic tells the user by email and updates the search index. During a viral spike, uploads keep working: the queue just grows for a while. ## In this group [#in-this-group] ### Queues: SQS [#queues-sqs] ### Notifications: SNS [#notifications-sns] ### Streaming [#streaming] ### More integration [#more-integration] ## Exam tips [#exam-tips] - **"Decouple", "absorb spikes", "the backend can't keep up"** → SQS between the tiers. - **"Send one message to many receivers"** → SNS (often SNS + SQS fan-out). - **"Real-time streaming", "clickstream", "IoT data", "replay"** → Kinesis Data Streams. - **"Load streaming data into S3 or Redshift with no code"** → Amazon Data Firehose. - **"Migrate an app that uses MQTT, AMQP or JMS without rewriting it"** → Amazon MQ. - **"React to an event in an AWS service", "cron job"** → EventBridge. - **"Orchestrate several Lambda functions with retries and human approval"** → Step Functions. ## Common traps [#common-traps] - **"Call the other service's API directly for reliability."** Direct calls couple the services; a queue keeps work safe when one side is down. - **"SNS keeps messages until a subscriber reads them."** SNS doesn't store messages; put an SQS queue behind it. ## AWS documentation [#aws-documentation] - [What is Amazon SQS?](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) - [What is Amazon SNS?](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) - [What is Amazon Kinesis Data Streams?](https://docs.aws.amazon.com/streams/latest/dev/introduction.html) - [What is Amazon EventBridge?](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) # Kinesis and Data Firehose (/docs/integration/kinesis) ## Kinesis Data Streams [#kinesis-data-streams]
![Kinesis Data Streams: producers such as click streams, IoT devices, and metrics and logs write records in real time to a stream made of shards; consumers such as applications, Lambda and Data Firehose read them; records are kept from 1 to 365 days and can be replayed](/diagrams/integration-kinesis-streams.light.svg) ![Kinesis Data Streams: producers such as click streams, IoT devices, and metrics and logs write records in real time to a stream made of shards; consumers such as applications, Lambda and Data Firehose read them; records are kept from 1 to 365 days and can be replayed](/diagrams/integration-kinesis-streams.dark.svg)
Many producers, a stream of shards, many consumers.
**[Amazon Kinesis Data Streams](/docs/glossary#term-kinesis-data-streams)** collects and stores **streaming data in real time**: a constant flow of small records such as click streams, IoT device readings, metrics and logs. - **Producers** (applications, the Kinesis Agent) write records to the stream. - **Consumers** (your applications, Lambda, Amazon Data Firehose, [Managed Service for Apache Flink](/docs/analytics/flink-msk)) read them. Key properties: - **Retention** from 24 hours up to **365 days**. - **Replay:** consumers can re-read (reprocess) old data, and several consumers can read the same data. - Data **can't be deleted** from Kinesis; it stays until it expires. - Records of up to **10 MiB** (the typical use is lots of small real-time records). - **Ordering** is guaranteed for records with the same **partition key**, which always go to the same **shard**. - **Encryption** at rest with KMS, in flight with HTTPS. - **Kinesis Producer Library (KPL)** and **Kinesis Client Library (KCL)** help write optimized producer and consumer applications. ### Shards and capacity modes [#shards-and-capacity-modes] A stream is made of **shards**. Each shard handles **1 MB/s or 1,000 records/s in** and **2 MB/s out** (shared by all standard consumers). With **enhanced fan-out**, each registered consumer gets its own **2 MB/s per shard**, pushed to it. - **Provisioned mode:** - you choose the number of shards; - you **scale manually** by adding or removing shards; - you **pay per shard per hour**. - **On-demand mode:** - no capacity to provision or manage; - starts at **4 MB/s or 4,000 records/s** of write capacity; - **scales automatically** based on the peak throughput seen in the **last 30 days**; - you **pay per stream per hour** and per GB in and out. AWS has since split on-demand into **On-demand Standard** (as in the slides) and **On-demand Advantage**, an account-level option with lower prices for steady use. The exam choice is unchanged: **predictable** traffic → provisioned; **unknown or spiky** traffic → on-demand. ## Amazon Data Firehose [#amazon-data-firehose]
![Amazon Data Firehose: sources such as applications, Kinesis Data Streams, CloudWatch Logs and AWS IoT send records to Firehose, which can transform them with Lambda, buffers and batches them, and writes them to destinations such as Amazon S3, Redshift, OpenSearch, Splunk, Datadog or any HTTP endpoint](/diagrams/integration-firehose.light.svg) ![Amazon Data Firehose: sources such as applications, Kinesis Data Streams, CloudWatch Logs and AWS IoT send records to Firehose, which can transform them with Lambda, buffers and batches them, and writes them to destinations such as Amazon S3, Redshift, OpenSearch, Splunk, Datadog or any HTTP endpoint](/diagrams/integration-firehose.dark.svg)
Collect, buffer, transform and deliver, with no code.
**[Amazon Data Firehose](/docs/glossary#term-amazon-data-firehose)** (formerly *Kinesis Data Firehose*) **loads streaming data into storage and analytics services**, fully managed: - **Sources:** applications, clients and SDKs, the Kinesis Agent, **Kinesis Data Streams**, **CloudWatch Logs and Events**, **AWS IoT**. - **Destinations:** - AWS: **Amazon S3**, **Amazon Redshift** (through S3), **Amazon OpenSearch Service**, Apache Iceberg tables; - third-party partners: **Splunk**, **Datadog**, **New Relic**, **MongoDB** and others; - any **custom HTTP endpoint**. - **Automatic scaling, serverless, pay for what you use.** - **Near real time:** Firehose **buffers** records and writes them in **batches**, by size or time (for example every 60 seconds). - **Formats:** CSV, JSON, Parquet, Avro, raw text, binary. It can **convert to Parquet or ORC** and **compress** with gzip or snappy. - **Transformations** with **AWS Lambda**, for example CSV to JSON. - Records up to about **1 MB**. **All or failed** data can be backed up to an S3 bucket. ## Kinesis Data Streams vs Data Firehose [#kinesis-data-streams-vs-data-firehose] | | Data Streams | Data Firehose | | --- | --- | --- | | Purpose | Collect streams | Load into storage | | Code | Write producer and consumer | Fully managed | | Speed | Real time | Near real time | | Storage | Up to 365 days, replay | None, no replay | - **Data Streams:** streaming data collection; producer and consumer code; real time; provisioned or on-demand; data stored up to 365 days; replay. - **Data Firehose:** load streaming data into S3, Redshift, OpenSearch, third-party or HTTP; fully managed; near real time; automatic scaling; no data storage; no replay. ## Real-world examples [#real-world-examples] - **A mobile game** streams player events into Kinesis Data Streams; one consumer updates a live leaderboard, another detects cheating, and both can replay the last day after a bug fix. - **A website** sends its clickstream through Data Firehose to S3 as compressed Parquet files every 60 seconds, ready for Athena. - **A security team** streams CloudWatch Logs through Firehose to Splunk. ## Exam tips [#exam-tips] - **"Real-time streaming", "clickstream", "IoT telemetry", "process in real time", "replay"** → Kinesis Data Streams. - **"Several applications must read the same stream"** → Kinesis Data Streams (enhanced fan-out for many consumers). - **"Order per device or user"** → same partition key → same shard. - **"Load streaming data into S3, Redshift, OpenSearch or Splunk with the least effort"** → Data Firehose. - **"Convert incoming JSON to Parquet before S3"** → Firehose format conversion (or Lambda transformation). - **"Near real time is fine (about a minute)"** → Firehose; **"milliseconds"** → Data Streams. - **"Unpredictable stream throughput, no shard management"** → on-demand mode. ## Common traps [#common-traps] - **"Firehose stores data and allows replay."** It only delivers; use Data Streams for storage and replay. - **"Kinesis Data Streams writes to S3 by itself."** You need a consumer, such as Firehose. - **"Delete records from a stream after processing."** Records stay until they expire. ## Hands-on lab: a Firehose stream to S3 [#hands-on-lab-a-firehose-stream-to-s3] **Goal:** send test data through Data Firehose into an S3 bucket. Firehose charges per GB ingested (minimum 5 KB per record); the built-in test data for a few minutes costs **a cent or two**. Any Region works. ### Create a bucket [#create-a-bucket] Create an S3 bucket `saa-firehose-`. ### Create the Firehose stream [#create-the-firehose-stream] **Amazon Data Firehose → Create Firehose stream**. Source **Direct PUT**, destination **Amazon S3**, name `saa-stream`, bucket `saa-firehose-`. Under **Buffer hints**, set the interval to **60 seconds**. Create. ### Send test data [#send-test-data] Open `saa-stream` → **Test with demo data → Start sending demo data**. After a minute, **Stop**. Wait another minute, then open the bucket: folders by year/month/day/hour contain files of batched stock-ticker records. **Expected result:** a stream of records delivered to S3 in batches, with no code. **Clean up:** delete `saa-stream`, then empty and delete the bucket. ## AWS documentation [#aws-documentation] - [What is Amazon Kinesis Data Streams?](https://docs.aws.amazon.com/streams/latest/dev/introduction.html) - [Choose the data stream capacity mode](https://docs.aws.amazon.com/streams/latest/dev/how-do-i-size-a-stream.html) - [Kinesis Data Streams quotas and limits](https://docs.aws.amazon.com/streams/latest/dev/service-sizes-and-limits.html) - [Develop enhanced fan-out consumers](https://docs.aws.amazon.com/streams/latest/dev/enhanced-consumers.html) - [What is Amazon Data Firehose?](https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html) # Amazon SES and Pinpoint (/docs/integration/ses-pinpoint) SES and Pinpoint are in the course but not on the current SAA-C03 list of in-scope services. Read this page to recognize them, especially in wrong answers. ## Amazon SES [#amazon-ses] **[Amazon SES](/docs/glossary#term-amazon-ses)** (Simple Email Service) is a fully managed service to **send emails** securely, globally and at scale. - **Inbound and outbound** email. - **Reputation dashboard**, performance insights and anti-spam feedback. - **Statistics:** deliveries, bounces, feedback loop results, email opens. - Supports **DKIM** (DomainKeys Identified Mail) and **SPF** (Sender Policy Framework), which prove your emails really come from your domain. - **Flexible IP deployment:** shared, dedicated, or your own IP addresses. - Send email from your application using the **console, the APIs or SMTP**. - **Use cases:** transactional emails (receipts, password resets), marketing and bulk emails. SNS can also send email, but only simple notifications to subscribers of a topic; SES is for proper application email at scale. ## Amazon Pinpoint [#amazon-pinpoint] **Amazon Pinpoint** was a scalable **two-way** (outbound and inbound) **marketing communications** service: - email, SMS, push, voice and in-app messaging; - **segments** and personalized content for the right customers; - receiving **replies**; - scaling to billions of messages a day; - **use cases:** marketing, bulk and transactional SMS campaigns. **Compared with SNS and SES:** with SNS and SES you manage each message's audience, content and delivery schedule yourself. With Pinpoint you created message **templates**, delivery **schedules**, highly targeted **segments** and full **campaigns**. **AWS ended support for Amazon Pinpoint on 30 October 2026.** Its SMS, voice, mobile push and one-time-password APIs carry on as **AWS End User Messaging**; email moves to **Amazon SES**; segments, campaigns and journeys move to **Amazon Connect**. ## Exam tips [#exam-tips] - **"Send transactional or marketing email from an application"** → SES. - **"Simple notifications to subscribers (email, SMS)"** → SNS. - **"Marketing campaigns with segments and templates"** → was Pinpoint; now Amazon Connect and End User Messaging. ## Common traps [#common-traps] - **"Use SES to fan out messages to SQS queues."** That's SNS. ## AWS documentation [#aws-documentation] - [What is Amazon SES?](https://docs.aws.amazon.com/ses/latest/dg/Welcome.html) - [Amazon Pinpoint end of support](https://docs.aws.amazon.com/pinpoint/latest/userguide/migrate.html) # SNS fan-out and filtering (/docs/integration/sns-fan-out) ## SNS + SQS fan-out [#sns--sqs-fan-out]
![SNS plus SQS fan-out: the buying service publishes once to an SNS topic, and each subscribed SQS queue, one for the fraud service and one for the shipping service, gets its own copy to process at its own pace; each queue policy must allow SNS to write, and it works across Regions](/diagrams/integration-sns-fanout.light.svg) ![SNS plus SQS fan-out: the buying service publishes once to an SNS topic, and each subscribed SQS queue, one for the fraud service and one for the shipping service, gets its own copy to process at its own pace; each queue policy must allow SNS to write, and it works across Regions](/diagrams/integration-sns-fanout.dark.svg)
Push once to SNS, receive in every queue.
**[Fan-out](/docs/glossary#term-fan-out)** combines the two services: - **Push once to SNS; every SQS queue subscribed to the topic receives a copy.** - **Fully decoupled, no data loss:** SNS delivers to the queues, and SQS keeps each copy until its consumer processes it. - SQS adds **persistence**, **delayed processing** and **retries** of work. - You can **add more queues** (more consumer services) over time without touching the producer. - Each **SQS queue's access policy must allow SNS to write** to it. - **Cross-Region delivery:** a topic can deliver to queues in other Regions. ### Application: S3 events to several queues [#application-s3-events-to-several-queues] For the same combination of **event type** (for example *object created*) and **prefix** (for example `images/`), S3 allows only **one event notification rule**. To send the same S3 event to several SQS queues, send it to an **SNS topic** and fan out from there: to queues, a Lambda function, and anything else. ### Application: SNS to S3 through Firehose [#application-sns-to-s3-through-firehose] SNS can deliver to **Amazon Data Firehose**, so you can store every message published to a topic: buying service → SNS topic → Firehose → **Amazon S3** (or any other Firehose destination). ## SNS FIFO topics [#sns-fifo-topics] A **FIFO topic** keeps messages in order, like an [SQS FIFO queue](/docs/integration/sqs-fifo-patterns): - **ordering** by message group ID (messages in the same group are delivered in order); - **deduplication**, using a deduplication ID or content-based deduplication; - subscribers can be **SQS FIFO** and **SQS standard** queues; - **limited throughput**, the same as SQS FIFO (300 messages per second per message group, 3,000 per topic by default). **SNS FIFO + SQS FIFO** fan-out is the pattern when you need **fan-out + ordering + deduplication**. ## Message filtering [#message-filtering]
![SNS message filtering: a new order with state placed is published to the topic; it reaches the queue whose filter policy is state placed and the queue with no filter policy, but not the queues filtering on cancelled or declined](/diagrams/integration-sns-filtering.light.svg) ![SNS message filtering: a new order with state placed is published to the topic; it reaches the queue whose filter policy is state placed and the queue with no filter policy, but not the queues filtering on cancelled or declined](/diagrams/integration-sns-filtering.dark.svg)
Each subscription takes only the messages it wants.
- A **[filter policy](/docs/glossary#term-sns-filter-policy)** is a JSON policy on a **subscription** that says which messages it receives, based on message **attributes** or the message **body**. - A subscription **without** a filter policy receives **every** message. - Example: a buying service publishes orders with `state` = `placed`, `cancelled` or `declined`. The "placed orders" queue filters on `placed`, the "cancelled" queue and an email subscription filter on `cancelled`, and an "all orders" queue has no filter. ## Real-world examples [#real-world-examples] - **An e-commerce site** publishes each order once; separate queues feed fraud checks, shipping and analytics, and a new loyalty service is added later with one new subscription. - **A photo app** fans out each S3 upload event through SNS to a thumbnail queue, a moderation queue and a Lambda function. - **A price feed** uses an SNS FIFO topic and SQS FIFO queues so every store gets price changes in order. ## Exam tips [#exam-tips] - **"One event, processed independently by several services"** → SNS + SQS fan-out. - **"Send the same S3 event to several queues"** → S3 → SNS → SQS queues. - **"Fan-out with ordering and deduplication"** → SNS FIFO + SQS FIFO. - **"Each subscriber should only get some messages"** → SNS filter policies. - **"Store all messages from a topic in S3"** → SNS → Data Firehose → S3. - **"Queue doesn't receive messages from the topic"** → the queue's access policy must allow SNS. ## Common traps [#common-traps] - **"Create several S3 event rules with the same prefix and event type."** S3 allows only one; fan out with SNS. - **"Publish the same message to each queue from the producer."** That couples the producer to every consumer; publish once to SNS. ## Hands-on lab: SNS to two queues [#hands-on-lab-sns-to-two-queues] **Goal:** fan out one message to two SQS queues, one with a filter. A few requests cost **far less than a cent**. Any Region works. **Before you start:** have the `saa-alerts` topic from the [SNS lab](/docs/integration/sns#hands-on-lab-an-email-notification). ### Create two queues and subscribe them [#create-two-queues-and-subscribe-them] Create standard queues `saa-all` and `saa-cancelled`. For each, open it → **Subscribe to Amazon SNS topic** → `saa-alerts`. The console adds the access policy that lets SNS write to the queue. ### Add a filter policy [#add-a-filter-policy] In SNS, open the `saa-cancelled` subscription → **Edit → Subscription filter policy**, scope **Message attributes**: `{"state": ["cancelled"]}`. Save. ### Publish two messages [#publish-two-messages] Publish to `saa-alerts` with a message attribute `state` (String) = `placed`, then another with `state` = `cancelled`. Poll both queues: `saa-all` has two messages, `saa-cancelled` has only the cancelled one. **Expected result:** one publish, delivered to every matching queue. **Clean up:** delete the subscriptions, the `saa-alerts` topic and both queues. ## AWS documentation [#aws-documentation] - [Fanout Amazon SNS notifications to Amazon SQS queues](https://docs.aws.amazon.com/sns/latest/dg/sns-sqs-as-subscriber.html) - [Amazon SNS FIFO topics](https://docs.aws.amazon.com/sns/latest/dg/sns-fifo-topics.html) - [Amazon SNS message filtering](https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html) # Amazon SNS (/docs/integration/sns) ## What it is [#what-it-is] What if you want to send **one message to many receivers**? With direct integration, the buying service would call the email service, the fraud service, the shipping service and a queue, one by one, and need changing every time a receiver is added. **[Amazon SNS](/docs/glossary#term-amazon-sns)** (Simple Notification Service) uses **publish/subscribe** (pub/sub) instead:
![SNS publish/subscribe: the buying service publishes one message to an SNS topic, and every subscriber gets a copy: an SQS queue for the fraud service, a Lambda function for shipping, an email to the team and SMS or mobile push to customers](/diagrams/integration-sns-pubsub.light.svg) ![SNS publish/subscribe: the buying service publishes one message to an SNS topic, and every subscriber gets a copy: an SQS queue for the fraud service, a Lambda function for shipping, an email to the team and SMS or mobile push to customers](/diagrams/integration-sns-pubsub.dark.svg)
Publish once; every subscriber gets a copy.
- The **event producer** sends a message to **one SNS topic**. - **Event receivers** (subscriptions) listen to the topic: as many as you want. - **Each subscriber gets every message** (unless it uses a [filter policy](/docs/integration/sns-fan-out#message-filtering)). - Up to **12,500,000 subscriptions per topic**, and **100,000 topics** per account. ### Subscribers [#subscribers] - **SQS** queues, **Lambda** functions, **Amazon Data Firehose** streams (to S3, Redshift…); - **email**, **SMS** and **mobile push** notifications; - **HTTP(S)** endpoints. SNS **pushes** messages to subscribers; it **doesn't store** them. If a subscriber can't receive a message after SNS's retries, the message is lost for that subscriber (unless you give the subscription a dead-letter queue). Put an SQS queue behind SNS when messages must be kept. ## Services that publish to SNS [#services-that-publish-to-sns] Many AWS services send notifications straight to an SNS topic: - **CloudWatch alarms**, **AWS Budgets**, **Lambda**; - **Auto Scaling group** notifications, **S3 bucket events**, **DynamoDB**; - **CloudFormation** stack state changes, **AWS DMS** (new replication), **RDS events**, and more. ## How to publish [#how-to-publish] - **Topic publish** (using the SDK): 1. create a topic; 2. create one or more subscriptions; 3. publish to the topic. - **Direct publish** (for mobile app SDKs): 1. create a platform application; 2. create a platform endpoint; 3. publish to the platform endpoint. Works with Apple APNs, Google FCM, Amazon ADM and others. ## Security [#security] - **Encryption:** - **in flight**, using the HTTPS API; - **at rest**, with **KMS** keys; - **client-side**, if the client wants to encrypt and decrypt itself. - **Access control:** **IAM policies** control who can use the SNS API. - **SNS access policies** (resource policies, like S3 bucket policies) are useful for: - **cross-account** access to a topic; - letting **other services**, such as S3, **publish** to a topic. ## Real-world examples [#real-world-examples] - **A CloudWatch alarm** on high CPU publishes to an SNS topic that emails the on-call engineer and sends an SMS. - **An online shop** publishes each order to a topic; the warehouse, invoicing and analytics systems each subscribe. - **A mobile game** uses SNS mobile push to tell players their turn has come. ## Exam tips [#exam-tips] - **"Notify many receivers of one event", "pub/sub"** → SNS topic. - **"Email or SMS when a CloudWatch alarm fires"** → CloudWatch alarm → SNS. - **"Mobile push notifications"** → SNS. - **"Allow S3 (or another account) to publish to the topic"** → SNS access policy. ## Common traps [#common-traps] - **"SNS stores messages for subscribers that are offline."** It doesn't; use SQS behind SNS. - **"Consumers poll SNS."** SNS pushes to subscribers. ## Hands-on lab: an email notification [#hands-on-lab-an-email-notification] **Goal:** create a topic, subscribe your email address and publish a message. The first 1,000 email notifications each month are free, and a few API calls cost **nothing measurable**. Any Region works. ### Create a topic [#create-a-topic] **SNS → Topics → Create topic**, type **Standard**, name `saa-alerts`. Create. ### Subscribe your email [#subscribe-your-email] **Create subscription**: protocol **Email**, endpoint your email address. Open the confirmation email and choose **Confirm subscription**. ### Publish [#publish] Back on the topic, **Publish message**: subject `Test`, body `Hello from SNS`. Publish. The email arrives within seconds. **Expected result:** one publish delivered to your inbox through the topic. **Clean up:** keep `saa-alerts` for the [fan-out lab](/docs/integration/sns-fan-out#hands-on-lab-sns-to-two-queues), or delete the subscription and the topic. ## AWS documentation [#aws-documentation] - [What is Amazon SNS?](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) - [Amazon SNS endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/sns.html) - [Amazon SNS message delivery retries](https://docs.aws.amazon.com/sns/latest/dg/sns-message-delivery-retries.html) # SQS FIFO and patterns (/docs/integration/sqs-fifo-patterns) ## FIFO queues [#fifo-queues]
![An SQS FIFO queue: messages sent in the order 1, 2, 3, 4 are received in the same order within a message group ID, duplicates sent within 5 minutes are removed, and throughput is 300 messages a second, or 3,000 with batching](/diagrams/integration-sqs-fifo.light.svg) ![An SQS FIFO queue: messages sent in the order 1, 2, 3, 4 are received in the same order within a message group ID, duplicates sent within 5 minutes are removed, and throughput is 300 messages a second, or 3,000 with batching](/diagrams/integration-sqs-fifo.dark.svg)
First in, first out, and no duplicates.
A **[FIFO queue](/docs/glossary#term-fifo-queue)** (First In, First Out) keeps messages **in order**. Its name must end in `.fifo`. - **Ordering by message group ID:** messages with the same **message group ID** (a mandatory parameter) are received in the order they were sent. Different groups can be processed in parallel, for example one group per customer. - **Exactly-once processing:** FIFO removes **duplicates** sent within a **5-minute** deduplication interval, using a **deduplication ID** you send or **content-based deduplication** (a hash of the message body). - **Limited throughput:** **300 messages per second** without batching, **3,000 per second** with batching (10 messages per call). **High throughput mode** raises this a lot (up to 70,000 transactions per second per API action in the largest Regions), spread across message groups. Use FIFO when order matters (bank transactions, an order's status changes) or when duplicates would be harmful. ## Dead-letter queues [#dead-letter-queues]
![A dead-letter queue: when a message has been received from the source queue more times than maxReceiveCount without being deleted, for example because the consumer keeps failing on it, SQS moves it to the dead-letter queue for analysis](/diagrams/integration-sqs-dlq.light.svg) ![A dead-letter queue: when a message has been received from the source queue more times than maxReceiveCount without being deleted, for example because the consumer keeps failing on it, SQS moves it to the dead-letter queue for analysis](/diagrams/integration-sqs-dlq.dark.svg)
Messages that keep failing are set aside.
Some messages can never be processed: a malformed order, a bug triggered by one value. Without care, such a "poison" message is received, fails, reappears and fails again, forever. - A **[dead-letter queue (DLQ)](/docs/glossary#term-dead-letter-queue)** is a normal queue that receives messages a source queue gave up on. - The source queue's **redrive policy** sets **`maxReceiveCount`**: after a message has been received that many times without being deleted, SQS moves it to the DLQ. - The DLQ of a standard queue must be a standard queue, and the DLQ of a FIFO queue a FIFO queue. - After fixing the bug, **redrive** the messages back to the source queue. - A message's expiry is based on when it was **first** sent, so give the DLQ a **long retention period** (up to 14 days). Dead-letter queues and delay queues are only mentioned in passing in this section of the slides, but they're common exam topics. This section is written from the AWS documentation. ## Delay queues [#delay-queues] A **delay queue** hides new messages for a set time, **0 to 15 minutes**, before consumers can see them. You can also set a delay on single messages with a **message timer**. Use it when consumers need time before acting, for example waiting for a related record to be written first. ## SQS as a buffer to database writes [#sqs-as-a-buffer-to-database-writes]
![SQS as a buffer: during a traffic spike the front-end tier sends work to an SQS queue instead of writing to the database directly; the back-end tier reads the queue at a steady pace and writes to the database, which is never overloaded](/diagrams/integration-sqs-buffer.light.svg) ![SQS as a buffer: during a traffic spike the front-end tier sends work to an SQS queue instead of writing to the database directly; the back-end tier reads the queue at a steady pace and writes to the database, which is never overloaded](/diagrams/integration-sqs-buffer.dark.svg)
The queue absorbs the spike; the database never sees it.
If an application writes transactions straight to a database (RDS, Aurora, DynamoDB) and the load gets too big, **some transactions may be lost**: the database throttles or times out, and the request fails. Instead: 1. The front end **enqueues** each transaction in SQS (`SendMessage`), which never runs out of capacity. 2. A back-end tier **dequeues** messages (`ReceiveMessage`) and **inserts** them into the database at a pace it can handle, deleting each message only once it's written. Nothing is lost: if the database slows down, messages simply wait in the queue. This works when the client doesn't need an immediate answer from the database. ## Real-world examples [#real-world-examples] - **A stock trading app** puts each account's orders in a FIFO queue with the account ID as message group ID: orders for one account stay in order, different accounts are processed in parallel. - **A payment processor** uses FIFO deduplication so a retried request doesn't charge a customer twice. - **An image pipeline** sends files that crash the resizer to a DLQ after 5 attempts; engineers inspect them the next morning. - **A ticket sale** absorbs 50,000 orders a minute in SQS while the database writes them at 2,000 a minute. ## Exam tips [#exam-tips] - **"Order must be preserved", "no duplicates"** → SQS FIFO (message group ID, deduplication ID). - **"FIFO throughput"** → 300 msg/s, or 3,000 with batching (higher with high throughput mode). - **"Messages that fail repeatedly block the queue"** → dead-letter queue with `maxReceiveCount`. - **"Delay processing of new messages for a few minutes"** → delay queue (up to 15 minutes). - **"Database can't keep up with writes during spikes, don't lose any"** → SQS as a write buffer. ## Common traps [#common-traps] - **"Standard queues with a sequence number give the same result as FIFO."** Only FIFO guarantees order and deduplication. - **"Convert a standard queue to FIFO."** You can't; create a new FIFO queue. - **"The DLQ keeps messages for the DLQ's full retention from when they arrive there."** Expiry counts from the original send time. ## Hands-on lab: a FIFO queue and a dead-letter queue [#hands-on-lab-a-fifo-queue-and-a-dead-letter-queue] **Goal:** see deduplication in a FIFO queue, and a message move to a DLQ. A few dozen requests cost **far less than a cent**. Any Region works. ### Create the FIFO queue [#create-the-fifo-queue] **SQS → Create queue**, type **FIFO**, name `saa-orders.fifo`, tick **Content-based deduplication**. Create. ### Send a duplicate [#send-a-duplicate] **Send and receive messages**: body `order 1`, message group ID `customer-a`. Send it **twice**. Then send `order 2`. Poll: you receive `order 1` and `order 2` once each, in order. The duplicate was dropped. ### Add a dead-letter queue [#add-a-dead-letter-queue] Create a **standard** queue `saa-dlq`. Edit `saa-orders` (the standard queue from the [SQS lab](/docs/integration/sqs#hands-on-lab-send-receive-delete)): **Dead-letter queue → Enabled**, choose `saa-dlq`, **Maximum receives 2**. Set its visibility timeout to 5 seconds. ### Fail a message [#fail-a-message] Send a message to `saa-orders`. Poll it, don't delete it, wait 5 seconds; poll again, wait again. On the third poll it's gone from `saa-orders`; poll `saa-dlq` and it's there. **Expected result:** duplicates dropped by the FIFO queue, and a repeatedly failed message moved to the DLQ. **Clean up:** delete `saa-orders.fifo`, `saa-orders` and `saa-dlq`. ## AWS documentation [#aws-documentation] - [Amazon SQS FIFO queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html) - [High throughput for FIFO queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/high-throughput-fifo.html) - [Using dead-letter queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) - [Amazon SQS delay queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-delay-queues.html) # SQS vs SNS vs Kinesis (/docs/integration/sqs-sns-kinesis) ## The three models [#the-three-models]
![SQS versus SNS versus Kinesis: SQS is a queue where consumers pull messages that are deleted once processed, with many workers and ordering only with FIFO queues; SNS is publish/subscribe, pushing to subscribers without storing messages, so undelivered messages are lost, and it fans out to SQS; Kinesis Data Streams is a stream where consumers pull or receive pushed records that are kept 1 to 365 days, can be replayed and are ordered per shard](/diagrams/integration-sqs-sns-kinesis.light.svg) ![SQS versus SNS versus Kinesis: SQS is a queue where consumers pull messages that are deleted once processed, with many workers and ordering only with FIFO queues; SNS is publish/subscribe, pushing to subscribers without storing messages, so undelivered messages are lost, and it fans out to SQS; Kinesis Data Streams is a stream where consumers pull or receive pushed records that are kept 1 to 365 days, can be replayed and are ordered per shard](/diagrams/integration-sqs-sns-kinesis.dark.svg)
Queue, pub/sub and stream.
### Amazon SQS [#amazon-sqs] - Consumers **pull** data. - Data is **deleted** after being consumed. - **As many workers** (consumers) as you want; each message goes to one of them. - **No need to provision throughput.** - **Ordering** guaranteed only with **FIFO** queues. - Individual message **delay** is possible. ### Amazon SNS [#amazon-sns] - **Pushes** data to many subscribers (up to 12,500,000 per topic). - Data is **not persisted**: lost if not delivered. - **Pub/sub**, up to 100,000 topics. - **No need to provision throughput.** - Integrates with SQS for the **fan-out** pattern. - **FIFO** topics for ordering, with SQS FIFO. ### Amazon Kinesis Data Streams [#amazon-kinesis-data-streams] - **Standard:** consumers **pull** data, 2 MB/s per shard shared. - **Enhanced fan-out:** data is **pushed**, 2 MB/s per shard **per consumer**. - Data can be **replayed**. - Built for **real-time big data**, analytics and ETL. - **Ordering** at the **shard** level. - Data **expires** after a set number of days (1 to 365). - **Provisioned** or **on-demand** capacity. ## How to choose [#how-to-choose] - **One message, one worker, at its own pace** → SQS. - **One message, many different receivers** → SNS (with SQS queues behind it if they must not miss anything). - **A continuous stream that several consumers read, maybe again later** → Kinesis Data Streams. ## Exam tips [#exam-tips] - **"Decouple and buffer work"** → SQS. **"Notify many systems"** → SNS. **"Real-time analytics on a stream"** → Kinesis. - **"Replay messages from yesterday"** → Kinesis (or an SNS FIFO topic archive, or EventBridge archive); SQS deletes processed messages. - **"Several consumers each need every record"** → SNS fan-out or Kinesis, not one SQS queue. - **"No capacity planning at all"** → SQS or SNS (or Kinesis on-demand). ## Common traps [#common-traps] - **"SQS for broadcasting to several services."** Each SQS message is processed by one consumer; use SNS fan-out. - **"SNS for durable buffering."** SNS doesn't store messages. - **"Kinesis needs no capacity decisions in provisioned mode."** You choose and scale the shards. ## Check yourself [#check-yourself] Kinesis Data Streams: many consumers can read the same records, and retention (up to 365 days) allows replay. SNS topic with SQS queues subscribed for each service (fan-out): every service gets its own copy, kept in its queue until it's back. An SQS queue with an Auto Scaling group of workers scaling on the queue length. ## AWS documentation [#aws-documentation] - [Amazon SQS FAQs: SQS vs SNS vs Kinesis](https://aws.amazon.com/sqs/faqs/) - [What is Amazon SNS?](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) - [What is Amazon Kinesis Data Streams?](https://docs.aws.amazon.com/streams/latest/dev/introduction.html) # Amazon SQS (/docs/integration/sqs) ## What it is [#what-it-is] **[Amazon SQS](/docs/glossary#term-amazon-sqs)** (Simple Queue Service) is a fully managed **message queue**. Producers put messages in; consumers take them out and process them. It's AWS's oldest service (over 20 years old) and the standard way to **decouple applications**.
![An SQS queue: many producers send messages to the queue, which stores them; many consumers poll the queue, process messages and delete them](/diagrams/integration-sqs-queue.light.svg) ![An SQS queue: many producers send messages to the queue, which stores them; many consumers poll the queue, process messages and delete them](/diagrams/integration-sqs-queue.dark.svg)
Producers send; consumers poll, process and delete.
## Standard queues [#standard-queues] - **Nearly unlimited throughput**, and an unlimited number of messages in the queue. - Messages are kept **4 days by default**, up to **14 days**. - **Low latency:** under 10 ms to send and receive. - Each message can be up to **1 MiB**. For bigger payloads, store the data in S3 and send a pointer (the SQS Extended Client Library does this for you). - **At-least-once delivery:** a message can occasionally be delivered **more than once**. - **Best-effort ordering:** messages can arrive **out of order**. (For strict order, use [FIFO queues](/docs/integration/sqs-fifo-patterns).) For years the maximum message size was **256 KB**. AWS raised it to **1 MiB** in 2025, which the slides already show. Older practice questions may still say 256 KB. ## Producing messages [#producing-messages] - Producers send messages with the SDK's **`SendMessage`** API (or `SendMessageBatch`, up to 10 at once). - The message is **stored in SQS until a consumer deletes it** (or it expires after the retention period). - Example: send an order to be processed, with the order ID, customer ID and any attributes you want. ## Consuming messages [#consuming-messages] 1. **Consumers** (on EC2 instances, on-premises servers, or AWS Lambda) **poll** SQS for messages, receiving **up to 10** at a time. 2. They **process** each message, for example inserting the order into an RDS database. 3. They **delete** each message with the **`DeleteMessage`** API, so no other consumer handles it again. **Several consumers** can read the same queue **in parallel**: each receives different messages. If processing is too slow, **add more consumers** (scale horizontally). ### Scaling consumers with an Auto Scaling group [#scaling-consumers-with-an-auto-scaling-group]
![Scaling consumers on queue length: EC2 instances in an Auto Scaling group poll an SQS queue; CloudWatch tracks the queue length metric ApproximateNumberOfMessages, and when it is too high an alarm makes the group scale out](/diagrams/integration-sqs-asg.light.svg) ![Scaling consumers on queue length: EC2 instances in an Auto Scaling group poll an SQS queue; CloudWatch tracks the queue length metric ApproximateNumberOfMessages, and when it is too high an alarm makes the group scale out](/diagrams/integration-sqs-asg.dark.svg)
More messages waiting, more instances working.
Run the consumers in an [Auto Scaling group](/docs/scaling/auto-scaling-groups), and scale on the **queue length**: the CloudWatch metric **`ApproximateNumberOfMessages`**. When the backlog grows past a threshold, an alarm makes the group add instances; when it shrinks, the group removes them. (AWS recommends refining this into a *backlog per instance* target, using a custom metric.) ## Security [#security] - **Encryption:** - **in flight**, using the HTTPS API; - **at rest**, with SQS-managed keys (SSE-SQS) or **KMS keys** (SSE-KMS); - **client-side**, if the client wants to encrypt and decrypt itself. - **Access control:** **IAM policies** control who can call the SQS API. - **SQS access policies** (resource policies, like S3 bucket policies) are useful for: - **cross-account** access to a queue; - letting **other services** such as SNS or S3 **write** to the queue. ## Visibility timeout [#visibility-timeout]
![The visibility timeout: when a consumer receives a message, it is hidden from other consumers for the visibility timeout, 30 seconds by default, so other receive requests do not return it; if it is not deleted before the timeout ends, it becomes visible and is returned again](/diagrams/integration-visibility-timeout.light.svg) ![The visibility timeout: when a consumer receives a message, it is hidden from other consumers for the visibility timeout, 30 seconds by default, so other receive requests do not return it; if it is not deleted before the timeout ends, it becomes visible and is returned again](/diagrams/integration-visibility-timeout.dark.svg)
A received message is hidden for a while, not removed.
- When a consumer receives a message, the message becomes **invisible** to other consumers for the **[visibility timeout](/docs/glossary#term-visibility-timeout)**: **30 seconds** by default (up to 12 hours). - That's the time the consumer has to **process and delete** it. - If the timeout ends before the message is deleted, the message becomes **visible again** and another consumer may receive it: it's **processed twice**. - A consumer that needs more time can call **`ChangeMessageVisibility`** to extend it. - Set it with care: - **too high** (hours): if a consumer crashes, the message waits a long time before anyone retries it; - **too low** (seconds): messages are handed out again while still being worked on, causing **duplicates**. ## Long polling [#long-polling] - When a consumer asks for messages and the queue is empty, it can **wait** for messages to arrive instead of getting an empty answer straight away. This is **[long polling](/docs/glossary#term-long-polling)**. - It **reduces the number of API calls** (and cost) and **reduces latency**: a message is returned as soon as it arrives. - The wait time is **1 to 20 seconds** (20 is best). - Long polling is preferable to short polling. Turn it on for the whole queue (*receive message wait time*) or per request with **`WaitTimeSeconds`**. ## Decoupling application tiers [#decoupling-application-tiers] A front-end web app receives requests (for example "process this video") and sends a message to SQS instead of doing the heavy work itself. A back-end fleet receives the messages and does the processing. Each tier has its own Auto Scaling group and scales on its own metric; the queue is effectively infinitely scalable in between. ## Real-world examples [#real-world-examples] - **An image site** queues resize jobs in SQS; EC2 workers in an Auto Scaling group scale with the queue length. - **An order system** sends orders to SQS so a database outage never loses an order: they wait in the queue until the database is back. - **A Lambda function** is triggered by an SQS queue to process each batch of messages, with no servers to run. ## Exam tips [#exam-tips] - **"Decouple tiers", "buffer requests", "handle traffic spikes"** → SQS. - **"Scale workers on the number of messages waiting"** → Auto Scaling on `ApproximateNumberOfMessages` (or backlog per instance). - **"Messages are processed twice"** → visibility timeout too short; raise it or call `ChangeMessageVisibility`. - **"Reduce empty responses and API costs"** → long polling (`WaitTimeSeconds` up to 20). - **"Let S3 or SNS send to a queue"**, **"cross-account access"** → SQS access policy. - **"Messages larger than 1 MiB"** → S3 plus a pointer (Extended Client Library). - **"Keep messages up to 14 days"** → set the retention period. ## Common traps [#common-traps] - **"SQS standard guarantees order and exactly-once delivery."** It's best-effort order and at-least-once; use FIFO for strict order. - **"Consumers don't need to delete messages."** Undeleted messages reappear after the visibility timeout. - **"SQS pushes messages to consumers."** Consumers poll (Lambda polls for you). ## Hands-on lab: send, receive, delete [#hands-on-lab-send-receive-delete] **Goal:** create a queue, send a message, and watch the visibility timeout in action. SQS charges per million requests; a few dozen requests cost **far less than a cent**. Any Region works. ### Create a queue [#create-a-queue] **SQS → Create queue**. Type **Standard**, name `saa-orders`. Set **Visibility timeout** to 30 seconds and **Receive message wait time** to 20 seconds (long polling). Keep the default encryption (SSE-SQS). Create. ### Send a message [#send-a-message] Open the queue → **Send and receive messages**. Body `{"orderId": 1, "item": "pencil"}`. Send. The queue shows 1 message available. ### Receive without deleting [#receive-without-deleting] Choose **Poll for messages**. The message appears, with a receive count of 1. Wait 30 seconds and poll again: it comes back, receive count 2. The visibility timeout ended and it became visible again. ### Delete it [#delete-it] Select the message and **Delete**. Poll again: the queue is empty (the poll waits up to 20 seconds, which is long polling). **Expected result:** a message that keeps coming back until it's deleted. **Clean up:** delete the `saa-orders` queue (or keep it for the next lab). ## AWS documentation [#aws-documentation] - [What is Amazon SQS?](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) - [Amazon SQS standard queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues.html) - [Amazon SQS message quotas](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/quotas-messages.html) - [Amazon SQS visibility timeout](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) - [Amazon SQS short and long polling](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) - [Encryption at rest in Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html) # AWS Step Functions (/docs/integration/step-functions) ## What it is [#what-it-is] **[AWS Step Functions](/docs/glossary#term-aws-step-functions)** builds **serverless visual workflows** (state machines) that **orchestrate** your Lambda functions and other AWS services. Instead of one Lambda function calling the next and handling every error itself, you describe the steps and the order in a workflow. Step Functions runs it, tracks each step, retries failures and shows the progress in the console.
![A Step Functions workflow for an order: validate the order; a choice checks if it is in stock; if not, notify the customer; if yes, charge the payment and reserve the stock in parallel, then ship the order](/diagrams/integration-step-functions.light.svg) ![A Step Functions workflow for an order: validate the order; a choice checks if it is in stock; if not, notify the customer; if yes, charge the payment and reserve the stock in parallel, then ship the order](/diagrams/integration-step-functions.dark.svg)
An order workflow with a choice and a parallel step.
## Features [#features] - **Sequence**, **parallel** branches, **conditions** (choice), **wait**, and **map** (run a step for each item in a list). - **Timeouts**, **retries** and **error handling** (catch a failure and go to another state). - **Integrations** with Lambda, **EC2**, **ECS**, **on-premises servers**, **API Gateway**, **SQS** queues, DynamoDB and over 200 AWS services. - **Human approval:** a workflow can pause, send a task token (for example by email), and wait until a person approves before continuing. - The workflow is defined in JSON (the Amazon States Language) or drawn in the visual editor, Workflow Studio. **Use cases:** order fulfilment, data processing, web applications, any workflow. ## Standard vs Express workflows [#standard-vs-express-workflows] - **Standard:** runs for up to **one year**; **exactly-once** execution; full execution history for 90 days; priced per state transition. For long-running, auditable workflows (payments, order processing, human approval). - **Express:** runs for up to **five minutes**; **at-least-once** execution; very high volume; priced per execution and duration. For high-volume event processing, such as streaming data or IoT ingestion. The slides cover Step Functions in one slide. Standard vs Express workflows come from the AWS documentation; they're useful when a question mentions duration or volume. ## Real-world examples [#real-world-examples] - **An insurance claim** workflow validates the claim, checks for fraud and waits for an adjuster's approval, sometimes for days: a Standard workflow. - **A video pipeline** transcodes a video into several formats in parallel with Lambda and ECS tasks, then updates a database. - **An IoT backend** runs a short Express workflow for each of 50,000 device messages a second. ## Exam tips [#exam-tips] - **"Orchestrate several Lambda functions", "visual workflow", "retries and error handling between steps"** → Step Functions. - **"Workflow needs human approval"** → Step Functions (task token / callback). - **"Long-running workflow, up to a year, exactly once"** → Standard workflow. - **"High-volume, short (under 5 minutes) event processing"** → Express workflow. ## Common traps [#common-traps] - **"Chain Lambda functions by calling each other."** Hard to manage and retry; Step Functions orchestrates them. - **"Step Functions can only call Lambda."** It integrates with EC2, ECS, SQS, API Gateway, on-premises activities and many more. ## Hands-on lab: a small workflow [#hands-on-lab-a-small-workflow] **Goal:** run a workflow with a choice and a wait step, and watch it in the console. Standard workflows cost $0.025 per 1,000 state transitions, so a handful of runs cost **far less than a cent**. Any Region works. ### Create the state machine [#create-the-state-machine] **Step Functions → Create state machine → Create from blank**. In Workflow Studio, drag a **Choice** state, a **Wait** state (3 seconds) on one branch, and **Pass** states named `Approved` and `Rejected`. Set the choice rule: if `$.amount` is less than 100, go to Wait → `Approved`; otherwise go to `Rejected`. Name it `saa-workflow`, type **Standard**, and create it with a new role. ### Run it twice [#run-it-twice] **Start execution** with input `{"amount": 50}`, then again with `{"amount": 500}`. In the **Graph view**, the first run goes through Wait to `Approved` (green), the second straight to `Rejected`. **Expected result:** two executions taking different paths, each step visible in the graph. **Clean up:** delete `saa-workflow` and the IAM role it created. ## AWS documentation [#aws-documentation] - [What is Step Functions?](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) - [Choosing workflow type in Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/choosing-workflow-type.html) # AWS CloudFormation (/docs/management/cloudformation) ## What it is [#what-it-is] **[AWS CloudFormation](/docs/glossary#term-aws-cloudformation)** is a **declarative way of outlining your AWS infrastructure**, for almost any resource. For example, within a CloudFormation **template**, you say: - I want a security group; - I want two EC2 instances using this security group; - I want an S3 bucket; - I want a load balancer (ELB) in front of these machines. Then CloudFormation creates them for you, **in the right order**, with the **exact configuration** you specified. The resources created from one template form a **stack**; delete the stack and its resources are deleted too. ```yaml Resources: NotesBucket: Type: AWS::S3::Bucket Properties: VersioningConfiguration: Status: Enabled ``` ## Benefits [#benefits] - **Infrastructure as code:** - no resources are created manually, which is excellent for control; - changes to the infrastructure are reviewed through code. - **Cost:** - each resource in the stack is tagged with an identifier, so you can see how much a stack costs; - you can estimate the costs of your resources from the template; - savings strategy: in dev, delete stacks automatically at 5 PM and re-create them at 8 AM, safely. - **Productivity:** - destroy and re-create an infrastructure on the cloud on the fly; - automated diagrams of your templates; - declarative programming: no need to work out ordering and orchestration. - **Don't re-invent the wheel:** use existing templates from the web and the documentation. - **Supports (almost) all AWS resources**; "custom resources" cover the rest. ## Infrastructure Composer [#infrastructure-composer] **Infrastructure Composer** shows a CloudFormation stack visually: all the **resources** and the **relations** between them (for example a WordPress stack's load balancer, launch configuration and database). You can also design a template by dragging components. The standalone Infrastructure Composer console closes on **7 December 2026**. The same visual editor stays on the CloudFormation console pages and in the AWS Toolkit for VS Code. ## CloudFormation service role [#cloudformation-service-role]
![CloudFormation service role: a user with only cloudformation permissions and iam:PassRole submits a template; CloudFormation uses a service role with s3 permissions to create the stack's S3 bucket, so the user never needs those permissions directly](/diagrams/mon-cfn-service-role.light.svg) ![CloudFormation service role: a user with only cloudformation permissions and iam:PassRole submits a template; CloudFormation uses a service role with s3 permissions to create the stack's S3 bucket, so the user never needs those permissions directly](/diagrams/mon-cfn-service-role.dark.svg)
CloudFormation acts with its own role, not the user's.
- A **[service role](/docs/glossary#term-cloudformation-service-role)** is an IAM role that allows CloudFormation to **create, update and delete stack resources on your behalf**. - It lets users create, update and delete stack resources **even if they don't have permissions** to work with those resources directly. - **Use cases:** - you want to achieve the **least privilege** principle; - but you don't want to give the user all the permissions needed to create the stack resources. - The user must have **`iam:PassRole`** permission (to hand the role to CloudFormation). ## StackSets [#stacksets] StackSets isn't in the slides, but multi-account deployment comes up in exam questions. This section is written from the AWS documentation. **[CloudFormation StackSets](/docs/glossary#term-cloudformation-stacksets)** create, update or delete stacks **across multiple accounts and Regions with a single operation**. An administrator account manages the template; with AWS Organizations, new accounts can get the stack automatically. ## Real-world examples [#real-world-examples] - **A start-up** keeps its whole environment (VPC, ALB, Auto Scaling group, RDS) in one template, and creates an identical staging copy in 20 minutes. - **A security team** uses StackSets to deploy the same IAM roles and Config rules to all 120 accounts of its organization. ## Exam tips [#exam-tips] - **"Infrastructure as code", "repeatable environments", "re-create the same infrastructure"** → CloudFormation. - **"Let users deploy stacks without giving them permissions on the resources"** → CloudFormation service role + `iam:PassRole`. - **"Deploy the same stack to many accounts and Regions"** → StackSets. ## Common traps [#common-traps] - **"The service role lets the user act on the resources directly."** Only CloudFormation uses the role; the user only needs `iam:PassRole` and CloudFormation permissions. - **"Delete a resource by hand from a stack."** Change the template and update the stack, or the stack drifts. ## Hands-on lab: a stack from a template [#hands-on-lab-a-stack-from-a-template] **Goal:** create and delete an S3 bucket with CloudFormation. CloudFormation is free for AWS resources, and an empty S3 bucket costs nothing. Any Region works. ### Write the template [#write-the-template] Save the YAML above as `bucket.yaml` on your computer. ### Create the stack [#create-the-stack] **CloudFormation → Create stack → With new resources → Upload a template file**, choose `bucket.yaml`, stack name `saa-bucket-stack`, then create. ### Look around [#look-around] Open the stack's **Events** and **Resources** tabs. Open the bucket from the Resources tab: versioning is enabled, and it carries `aws:cloudformation:stack-name` tags. **Expected result:** a bucket created by CloudFormation, with a name generated from the stack name. **Clean up:** delete the `saa-bucket-stack` stack; CloudFormation deletes the bucket. ## AWS documentation [#aws-documentation] - [What is AWS CloudFormation?](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) - [CloudFormation service role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-servicerole.html) - [Managing stacks across accounts and Regions with StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) - [What is AWS Infrastructure Composer?](https://docs.aws.amazon.com/infrastructure-composer/latest/dg/what-is-composer.html) # AWS CloudTrail (/docs/management/cloudtrail) ## What it is [#what-it-is]
![AWS CloudTrail: API calls made through the SDK, the CLI or the console, by users, roles and AWS services, are recorded by CloudTrail, which keeps 90 days of event history; a trail sends them to CloudWatch Logs for search and metric filters, or to an S3 bucket to keep them for years and query them with Athena](/diagrams/mon-cloudtrail.light.svg) ![AWS CloudTrail: API calls made through the SDK, the CLI or the console, by users, roles and AWS services, are recorded by CloudTrail, which keeps 90 days of event history; a trail sends them to CloudWatch Logs for search and metric filters, or to an S3 bucket to keep them for years and query them with Athena](/diagrams/mon-cloudtrail.dark.svg)
Every API call, recorded.
**[AWS CloudTrail](/docs/glossary#term-aws-cloudtrail)** provides **governance, compliance and audit** for your AWS account. - CloudTrail is **enabled by default**: the **event history** keeps 90 days of management events. - It records a **history of events and API calls** made within your account, by: - the **console**; - the **SDK**; - the **CLI**; - **AWS services** (acting on your behalf). - Create a **[trail](/docs/glossary#term-cloudtrail-trail)** to put logs from CloudTrail into **CloudWatch Logs** or **S3**. - A trail can apply to **all Regions** (the default) or a **single Region**. An **organization trail** logs every account in an AWS Organization. - **If a resource is deleted in AWS, investigate CloudTrail first!** ## CloudTrail events [#cloudtrail-events] - **Management events:** - operations performed **on resources** in your account; - examples: configuring security (IAM `AttachRolePolicy`), configuring rules for routing data (EC2 `CreateSubnet`), setting up logging (CloudTrail `CreateTrail`); - **by default, trails log management events**; - you can separate **read events** (that don't modify resources) from **write events** (that may modify resources). - **Data events:** - **not logged by default** (because they're high-volume operations); - S3 object-level activity (`GetObject`, `DeleteObject`, `PutObject`), with read and write separated; - Lambda function execution activity (the `Invoke` API). - **Network activity events** (newer): API calls made through VPC endpoints, to see activity inside your VPC. - **CloudTrail Insights events:** see below. ## CloudTrail Insights [#cloudtrail-insights]
![CloudTrail Insights: it learns a baseline from normal management events, then watches for unusual API call rates or error rates; the resulting Insights events appear in the CloudTrail console, are stored in S3 with the trail, and are sent to EventBridge to automate a response](/diagrams/mon-cloudtrail-insights.light.svg) ![CloudTrail Insights: it learns a baseline from normal management events, then watches for unusual API call rates or error rates; the resulting Insights events appear in the CloudTrail console, are stored in S3 with the trail, and are sent to EventBridge to automate a response](/diagrams/mon-cloudtrail-insights.dark.svg)
Spot activity that doesn't look normal.
Enable **[CloudTrail Insights](/docs/glossary#term-cloudtrail-insights)** to **detect unusual activity** in your account: - inaccurate resource provisioning; - hitting service limits; - bursts of AWS IAM actions; - gaps in periodic maintenance activity. CloudTrail Insights **analyzes normal management events to create a baseline**, then **continuously analyzes write events** (call rates, and error rates) to detect unusual patterns (it can now also watch data events): - anomalies appear in the **CloudTrail console**; - the event is sent to **S3**; - an **EventBridge** event is generated, for automation. ## Events retention [#events-retention] - Events are stored for **90 days** in CloudTrail. - To keep events **beyond this period**, log them to **S3** with a trail and use **Athena** to query them. **CloudTrail Lake** is another option: a managed store where you keep events (up to years) and query them with SQL. ## EventBridge: intercept API calls [#eventbridge-intercept-api-calls]
![Reacting to an API call: a user calls DeleteTable on DynamoDB, CloudTrail records the call, an EventBridge rule matches the event, and SNS alerts the security team](/diagrams/mon-cloudtrail-eventbridge.light.svg) ![Reacting to an API call: a user calls DeleteTable on DynamoDB, CloudTrail records the call, an EventBridge rule matches the event, and SNS alerts the security team](/diagrams/mon-cloudtrail-eventbridge.dark.svg)
Turn any API call into an alert.
Every API call that CloudTrail logs becomes an event in **[EventBridge](/docs/integration/eventbridge#intercepting-api-calls)**, so a rule can react to it: - **DynamoDB `DeleteTable`** → alert through SNS; - a user **assumes a role** (`AssumeRole` in IAM) → SNS; - someone edits security group inbound rules (EC2 **`AuthorizeSecurityGroupIngress`**) → SNS. ## Real-world examples [#real-world-examples] - **A production database disappears** at 3 AM. CloudTrail event history shows `DeleteDBInstance` called by a CI/CD role using a misconfigured script. - **A security team** gets an SNS alert within a minute whenever anyone opens port 22 to `0.0.0.0/0`, through CloudTrail and EventBridge. ## Exam tips [#exam-tips] - **"Who deleted / modified the resource?", "audit API calls"** → CloudTrail. - **"Keep CloudTrail logs longer than 90 days and analyse them"** → trail to S3 + Athena. - **"Log S3 object-level operations (GetObject, PutObject)"** → enable **data events**. - **"Detect unusual API activity", "burst of IAM actions"** → CloudTrail Insights. - **"Alert when a specific API call happens"** → CloudTrail + EventBridge rule + SNS. - **"Audit all accounts in an organization"** → organization trail. ## Common traps [#common-traps] - **"S3 GetObject calls are in CloudTrail by default."** Data events must be enabled on a trail. - **"CloudTrail keeps events forever."** Event history is 90 days; use a trail to S3 for longer. ## Hands-on lab: find who did something [#hands-on-lab-find-who-did-something] **Goal:** look up an API call in CloudTrail event history. Event history is free. Creating and deleting the security group below is free too. Any Region works. ### Make a change [#make-a-change] **EC2 → Security groups → Create security group** named `saa-trail-test` in the default VPC. ### Find it [#find-it] Wait about 5 minutes, then open **CloudTrail → Event history**. Filter on **Event name = CreateSecurityGroup**. Open the event and read its JSON: `userIdentity`, `sourceIPAddress`, `eventTime`. **Expected result:** an event that shows your user (or role), your IP address and the time. **Clean up:** delete the `saa-trail-test` security group. ## AWS documentation [#aws-documentation] - [What is AWS CloudTrail?](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) - [CloudTrail concepts](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-concepts.html) - [Working with CloudTrail Insights](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-insights-events-with-cloudtrail.html) # CloudWatch alarms (/docs/management/cloudwatch-alarms) ## Alarms [#alarms] **[CloudWatch alarms](/docs/glossary#term-cloudwatch-alarm)** trigger notifications or actions for **any metric**. - Various options: sampling, percentage, maximum, minimum… - **Alarm states:** - **OK**; - **INSUFFICIENT_DATA**; - **ALARM**. - **Period:** the length of time, in seconds, over which the metric is evaluated. High-resolution custom metrics allow periods of 10 or 30 seconds, or multiples of 60. ## Alarm targets [#alarm-targets]
![CloudWatch alarm targets: when a metric crosses its threshold the alarm moves between the OK, INSUFFICIENT_DATA and ALARM states and can stop, terminate, reboot or recover an EC2 instance, scale an Auto Scaling group, notify SNS, invoke a Lambda function, or create a Systems Manager OpsItem or incident](/diagrams/mon-alarm-targets.light.svg) ![CloudWatch alarm targets: when a metric crosses its threshold the alarm moves between the OK, INSUFFICIENT_DATA and ALARM states and can stop, terminate, reboot or recover an EC2 instance, scale an Auto Scaling group, notify SNS, invoke a Lambda function, or create a Systems Manager OpsItem or incident](/diagrams/mon-alarm-targets.dark.svg)
What an alarm can do when it fires.
- **EC2 actions:** stop, terminate, reboot or recover an EC2 instance. - Trigger an **Auto Scaling** action. - Send a notification to **SNS** (from which you can do pretty much anything). Alarms can now also **invoke a Lambda function directly** (no SNS topic in between) and create **Systems Manager OpsItems or incidents**. ## Composite alarms [#composite-alarms]
![A composite alarm: alarm A watches the instance's CPU and alarm B its IOPS; the composite alarm goes into ALARM only when A AND B are both in ALARM, and then sends one alert to SNS](/diagrams/mon-composite-alarm.light.svg) ![A composite alarm: alarm A watches the instance's CPU and alarm B its IOPS; the composite alarm goes into ALARM only when A AND B are both in ALARM, and then sends one alert to SNS](/diagrams/mon-composite-alarm.dark.svg)
Alert only when several things go wrong together.
- A normal CloudWatch alarm watches **a single metric**. - **[Composite alarms](/docs/glossary#term-composite-alarm)** monitor the **states of multiple other alarms**. - **AND** and **OR** conditions (and NOT). - Helpful to **reduce "alarm noise"**: for example, high CPU alone is normal during a batch job, but high CPU **and** high IOPS means trouble. ## EC2 instance recovery [#ec2-instance-recovery]
![EC2 instance recovery: a CloudWatch alarm on StatusCheckFailed_System monitors the instance; when the underlying hardware fails it alerts an SNS topic and recovers the instance onto new hardware with the same private and public IP addresses, Elastic IP, metadata and placement group](/diagrams/mon-ec2-recovery.light.svg) ![EC2 instance recovery: a CloudWatch alarm on StatusCheckFailed_System monitors the instance; when the underlying hardware fails it alerts an SNS topic and recovers the instance onto new hardware with the same private and public IP addresses, Elastic IP, metadata and placement group](/diagrams/mon-ec2-recovery.dark.svg)
Move the same instance to healthy hardware.
**Status checks:** - **Instance status:** checks the EC2 virtual machine (software, network config of the instance). - **System status:** checks the **underlying hardware** (AWS's host). - **Attached EBS status:** checks the attached EBS volumes. **Recovery:** an alarm on **`StatusCheckFailed_System`** with the **recover** action moves the instance to new hardware and keeps the **same private and public IPv4 addresses, Elastic IP, metadata and placement group**. Supported instance types now also have **simplified automatic recovery**, turned on by default, which does the same without an alarm. ## Good to know [#good-to-know]
![An alarm on logs: a metric filter on a log group counts lines containing ERROR and publishes a metric; a CloudWatch alarm on that metric alerts the on-call team through SNS when there are more than 10 a minute](/diagrams/mon-metric-filter.light.svg) ![An alarm on logs: a metric filter on a log group counts lines containing ERROR and publishes a metric; a CloudWatch alarm on that metric alerts the on-call team through SNS when there are more than 10 a minute](/diagrams/mon-metric-filter.dark.svg)
Turn log lines into a metric, then alarm on it.
- Alarms can be created on **CloudWatch Logs metric filters**: a **[metric filter](/docs/glossary#term-metric-filter)** turns matching log lines into a metric. - To **test alarms and notifications**, set the alarm state to ALARM with the CLI: ```bash aws cloudwatch set-alarm-state --alarm-name "myalarm" \ --state-value ALARM --state-reason "testing purposes" ``` ## CloudWatch Network Synthetic Monitor [#cloudwatch-network-synthetic-monitor] - **Monitors and detects network issues** between your apps hosted on AWS and your **on-premises data center**. - Identifies network performance degradation (**packet loss, latency**, jitter…). - **No agents** to install. - Tests **ICMP or TCP** traffic to IPv4 or IPv6 on-premises destinations through **Direct Connect** or **Site-to-Site VPN** connections. - Publishes data to **CloudWatch metrics**. ## Real-world examples [#real-world-examples] - **A web team** alarms when the ALB's 5xx error count is above 50 for 3 minutes, and SNS pages the on-call engineer. - **A trading firm** uses Network Synthetic Monitor to alert when packet loss on its Direct Connect link rises above 1%. ## Exam tips [#exam-tips] - **"Automatically recover an EC2 instance on hardware failure, keeping its IP"** → alarm on `StatusCheckFailed_System` with the recover action (or simplified automatic recovery). - **"Reduce alarm noise", "alert only when several conditions are true"** → composite alarm. - **"Alarm on errors in logs"** → metric filter + alarm. - **"Test an alarm's notification"** → `set-alarm-state`. - **"Monitor latency and packet loss to on premises over Direct Connect or VPN, no agents"** → Network Synthetic Monitor. ## Common traps [#common-traps] - **"Recover changes the instance's IP."** Recovery keeps the IPs; a stop and start changes the public IP (unless it's an Elastic IP). - **"An alarm can watch several metrics at once."** One metric (or metric math); combine alarms with a composite alarm. ## Hands-on lab: an alarm with an email [#hands-on-lab-an-alarm-with-an-email] **Goal:** create an alarm, send its notification to your email, and test it. A standard alarm costs about $0.10 a month, charged by the hour, and SNS emails are about $2 per 100,000, so this lab costs **less than a cent**. Any Region works. ### Create the alarm [#create-the-alarm] Use the `MyApp / ActiveUsers` metric from the [metrics lab](/docs/management/cloudwatch-metrics#hands-on-lab-publish-a-custom-metric) (or any metric). **CloudWatch → Alarms → Create alarm**, select the metric, condition **Greater than 1000**. ### Add the notification [#add-the-notification] Create a new SNS topic `saa-alarms` with your email address. Name the alarm `saa-test-alarm` and create it. Confirm the subscription email. ### Test it [#test-it] In CloudShell, run `set-alarm-state` with `--alarm-name saa-test-alarm`. **Expected result:** the alarm turns red for a moment and you receive an "ALARM" email. **Clean up:** delete the alarm and the `saa-alarms` topic. ## AWS documentation [#aws-documentation] - [Using Amazon CloudWatch alarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html) - [Alarm actions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/alarm-actions.html) - [Create a composite alarm](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Create_Composite_Alarm.html) - [Automatic instance recovery](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-recover.html) - [What is Network Synthetic Monitor?](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/what-is-network-monitor.html) # CloudWatch Insights (/docs/management/cloudwatch-insights) ## Four kinds of Insights [#four-kinds-of-insights] CloudWatch has several "Insights" features that give ready-made, deeper visibility than raw metrics: - **Container Insights:** ECS, EKS, Kubernetes on EC2, Fargate; metrics and logs (needs an agent on Kubernetes). - **Lambda Insights:** detailed metrics to troubleshoot serverless applications. - **Contributor Insights:** find the **top-N contributors** through CloudWatch Logs. - **Application Insights:** automatic dashboards to troubleshoot your application and related AWS services. ## Container Insights [#container-insights] **[Container Insights](/docs/glossary#term-container-insights)** collects, aggregates and summarizes **metrics and logs from containers**. - Available for containers on: - Amazon **ECS**; - Amazon **EKS**; - **Kubernetes** platforms on EC2; - **Fargate** (both for ECS and EKS). - In EKS and Kubernetes, Container Insights uses a **containerized version of the CloudWatch agent** to discover containers (installed with the CloudWatch Observability add-on). ## Lambda Insights [#lambda-insights] **[Lambda Insights](/docs/glossary#term-lambda-insights)** is a monitoring and troubleshooting solution for serverless applications running on Lambda. - Collects, aggregates and summarizes **system-level metrics**: CPU time, memory, disk and network. - Collects diagnostic information such as **cold starts** and Lambda worker shutdowns. - Provided as a **Lambda layer** (a CloudWatch Lambda extension). ## Contributor Insights [#contributor-insights] **[Contributor Insights](/docs/glossary#term-contributor-insights)** analyzes log data and creates time series that show **contributor data**. - See metrics about the **top-N contributors**, the total number of unique contributors, and their usage. - This helps you find **top talkers** and understand **who or what is impacting system performance**. - Works for any AWS-generated logs (VPC Flow Logs, DNS…). - For example, find bad hosts, identify the **heaviest network users**, or find the URLs that generate the most errors. - Build rules from scratch, or use **sample rules** AWS has created. CloudWatch also provides built-in rules for metrics from other AWS services (such as DynamoDB). For example: VPC Flow Logs → CloudWatch Logs → Contributor Insights → the **top 10 IP addresses** by traffic. ## Application Insights [#application-insights] **[Application Insights](/docs/glossary#term-application-insights)** provides **automated dashboards** that show potential problems with monitored applications, to help isolate ongoing issues. - Your applications run on EC2 with selected technologies (Java, .NET, Microsoft IIS web server, databases such as SQL Server…). - It also covers related resources: EBS, RDS, ELB, Auto Scaling groups, Lambda, SQS, DynamoDB, S3, ECS, EKS, SNS, API Gateway… - **Powered by SageMaker AI** (machine learning). - Gives better visibility into application health, to **reduce the time to troubleshoot** and repair. - Findings and alerts are sent to **EventBridge** and **SSM OpsCenter**. ## Real-world examples [#real-world-examples] - **A platform team** turns on Container Insights for its EKS cluster to see which pods use the most memory. - **A security team** uses Contributor Insights on VPC Flow Logs to spot an instance suddenly sending far more traffic than any other. ## Exam tips [#exam-tips] - **"Metrics and logs for ECS, EKS, Fargate containers"** → Container Insights. - **"Troubleshoot Lambda performance, cold starts, memory"** → Lambda Insights. - **"Top-N", "heaviest users", "top talkers", "which IP generates the most traffic or errors"** → Contributor Insights. - **"Automatic dashboards for a .NET or SQL Server application on EC2"** → Application Insights. ## Common traps [#common-traps] - **"Contributor Insights for container metrics."** Containers → Container Insights; top-N from logs → Contributor Insights. ## Check yourself [#check-yourself] Send VPC Flow Logs to CloudWatch Logs and use a Contributor Insights rule to rank the top-N source IP addresses. ## AWS documentation [#aws-documentation] - [Container Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContainerInsights.html) - [Lambda Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights.html) - [Contributor Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html) - [Application Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html) # CloudWatch Logs (/docs/management/cloudwatch-logs) ## Log groups and streams [#log-groups-and-streams] **[CloudWatch Logs](/docs/glossary#term-cloudwatch-logs)** stores and analyses logs from your applications, systems and AWS services. - **Log groups:** an arbitrary name, usually representing an **application** (`/myapp/prod`). - **Log streams:** instances within the application, log files or containers. - **Expiration policies:** never expire (the default) or **1 day to 10 years**. - Logs are **encrypted by default**; you can use **KMS** with your own keys. - CloudWatch Logs can send logs to **S3** (exports), **Kinesis Data Streams**, **Data Firehose**, **Lambda** and **OpenSearch**. - **Live Tail** shows new log events as they arrive, for troubleshooting. - Two **log classes:** **Standard**, and the cheaper **Essentials** class (formerly Infrequent Access) with a subset of features, for logs you rarely look at. **Sources:** - the SDK, the **CloudWatch agent**; - **Elastic Beanstalk:** logs from the application; - **ECS:** logs from containers; - **Lambda:** function logs; - **VPC Flow Logs:** VPC traffic logs; - **API Gateway** access and execution logs; - **CloudTrail**, based on a filter; - **Route 53:** DNS query logs. ## CloudWatch Logs Insights [#cloudwatch-logs-insights] **[Logs Insights](/docs/glossary#term-cloudwatch-logs-insights)** **searches and analyses** log data stored in CloudWatch Logs. - Example: find a specific IP address in a log, count occurrences of "ERROR" in your logs. - A **purpose-built query language** (OpenSearch PPL and SQL also work): - it automatically discovers fields from AWS services and JSON log events; - fetch fields, filter on conditions, calculate aggregate statistics, sort, limit… - save queries and add them to **dashboards**. - Query **multiple log groups**, even in **different AWS accounts**. - It's a **query engine, not a real-time engine**. ```text fields @timestamp, @message | filter @message like /ERROR/ | stats count(*) as errors by bin(5m) ``` ## Exporting to S3 [#exporting-to-s3] - Export log data to S3 in batches with the **`CreateExportTask`** API. - Log data can take **up to 12 hours** to become available for export. - It's **not near real time or real time**: for that, use **subscriptions**. ## Subscriptions [#subscriptions]
![CloudWatch Logs subscriptions: a subscription filter selects log events and sends them in real time to a Lambda function (for example to load OpenSearch), to Firehose (near real time, to S3 or OpenSearch), or to Kinesis Data Streams for Flink or your own apps](/diagrams/mon-logs-subscriptions.light.svg) ![CloudWatch Logs subscriptions: a subscription filter selects log events and sends them in real time to a Lambda function (for example to load OpenSearch), to Firehose (near real time, to S3 or OpenSearch), or to Kinesis Data Streams for Flink or your own apps](/diagrams/mon-logs-subscriptions.dark.svg)
A real-time feed of log events.
- Get a **real-time feed of log events** from CloudWatch Logs for processing and analysis. - Send it to **Kinesis Data Streams**, **Data Firehose** or **Lambda** (see the [OpenSearch patterns](/docs/analytics/opensearch#patterns-cloudwatch-logs-and-kinesis)). - A **subscription filter** chooses which log events are delivered to your destination. - **Cross-account subscription:** send log events to a Kinesis stream or Firehose in a **different AWS account**. The recipient account creates a **destination** with a **destination access policy** allowing the sender, and an IAM role that can write to the stream. ### Multi-account, multi-Region aggregation [#multi-account-multi-region-aggregation]
![Aggregating logs from several accounts and Regions: CloudWatch Logs subscription filters in account A Region 1 and account B Regions 2 and 3 send log events to one Kinesis data stream in a central account, and Firehose delivers them to a single S3 bucket in near real time](/diagrams/mon-logs-aggregation.light.svg) ![Aggregating logs from several accounts and Regions: CloudWatch Logs subscription filters in account A Region 1 and account B Regions 2 and 3 send log events to one Kinesis data stream in a central account, and Firehose delivers them to a single S3 bucket in near real time](/diagrams/mon-logs-aggregation.dark.svg)
Every account's logs in one central bucket.
Subscription filters in each account and Region send logs to **one Kinesis data stream**, and **Firehose** delivers them to **one S3 bucket** in near real time. (CloudWatch Logs can now also centralize logs across accounts and Regions by itself.) ## CloudWatch agent for EC2 and on premises [#cloudwatch-agent-for-ec2-and-on-premises] - By default, **no logs from your EC2 instance** go to CloudWatch. - You need to run a **CloudWatch agent** on EC2 to push the log files you want. - Make sure **IAM permissions** are correct (an instance role). - The agent also runs **on premises**. **Two agents:** - **CloudWatch Logs agent:** the old version; can only send to CloudWatch Logs. - **[CloudWatch unified agent](/docs/glossary#term-cloudwatch-agent):** collects **logs** and **extra system-level metrics** such as RAM and processes. **Centralized configuration** in **SSM Parameter Store**. **Unified agent metrics**, collected directly on your Linux server or EC2 instance: - **CPU** (active, guest, idle, system, user, steal); - **disk** metrics (free, used, total) and disk I/O (writes, reads, bytes, IOPS); - **RAM** (free, inactive, used, total, cached); - **netstat** (TCP and UDP connections, packets, bytes); - **processes** (total, dead, blocked, idle, running, sleeping); - **swap space** (free, used, used %). Reminder: out-of-the-box EC2 metrics are only high level (CPU, disk I/O, network). ## Real-world examples [#real-world-examples] - **An operations team** runs a Logs Insights query across 40 Lambda log groups to find which function threw the most timeouts last night. - **A bank** keeps 7 years of logs: a subscription with Firehose writes them to S3 Glacier storage classes, and CloudWatch keeps only 30 days. ## Exam tips [#exam-tips] - **"Analyse or search logs with queries"** → Logs Insights. - **"Logs to S3 in batch"** → export (`CreateExportTask`, up to 12 hours). **"Real time / near real time"** → subscription filter to Kinesis, Firehose or Lambda. - **"Centralize logs from many accounts and Regions"** → subscriptions to one Kinesis stream (cross-account destination), then Firehose to S3. - **"Collect RAM, disk, processes from EC2 or on premises"** → CloudWatch unified agent. - **"No logs from EC2 in CloudWatch"** → install the agent and check the instance role permissions. ## Common traps [#common-traps] - **"EC2 sends its application logs to CloudWatch automatically."** Only with the agent. - **"Use export for real-time processing."** Exports can lag 12 hours; use subscriptions. - **"Logs Insights alerts in real time."** It's a query engine; for alerts use metric filters and alarms. ## Check yourself [#check-yourself] The agent lab needs an EC2 instance and an IAM role (covered later in [Systems Manager](/docs/management/systems-manager)), so instead: In each account, a CloudWatch Logs subscription filter sends log events to a cross-account destination in a central account: a Kinesis data stream feeding Firehose, which writes to the central S3 bucket. Run a CloudWatch Logs Insights query on the log group, filtering for 500 status codes and counting by 1-minute bins. ## AWS documentation [#aws-documentation] - [What is Amazon CloudWatch Logs?](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) - [Log classes](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch_Logs_Log_Classes.html) - [Analyzing log data with CloudWatch Logs Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AnalyzingLogData.html) - [Exporting log data to Amazon S3](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/S3Export.html) - [Real-time processing of log data with subscriptions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Subscriptions.html) - [Collect metrics, logs, and traces using the CloudWatch agent](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html) # CloudWatch metrics (/docs/management/cloudwatch-metrics) ## Metrics [#metrics] **[Amazon CloudWatch](/docs/glossary#term-amazon-cloudwatch)** provides **metrics for every service** in AWS. - A **metric** is a variable to monitor: `CPUUtilization`, `NetworkIn`… - Metrics belong to **namespaces** (`AWS/EC2`, `AWS/RDS`, or your own, such as `MyApp`). - A **dimension** is an attribute of a metric: instance ID, environment… **Up to 30 dimensions** per metric. - Metrics have **timestamps**. - You can build **CloudWatch dashboards** of metrics. - You can create **custom metrics**, for example for **RAM** (EC2 doesn't publish memory usage by itself). **Resolution and retention:** - AWS services publish **standard resolution** metrics: one data point per minute (EC2 basic monitoring: every 5 minutes; **detailed monitoring**: every minute, for a charge). - Custom metrics can be **high resolution**, down to **1 second**. - Data is kept for **15 months**, and gets coarser with age: 1-minute points for 15 days, 5-minute points for 63 days, 1-hour points for 455 days. ## Custom metrics [#custom-metrics] You publish a custom metric with the `PutMetricData` API (or the CloudWatch agent, which collects RAM, disk space and processes for you): ```bash aws cloudwatch put-metric-data --namespace "MyApp" \ --metric-name ActiveUsers --dimensions Env=prod --value 42 ``` - Use **dimensions** to split it (by instance, by environment). - Choose the **storage resolution**: 60 seconds (standard) or 1 second (high resolution, more cost). ## CloudWatch metric streams [#cloudwatch-metric-streams]
![CloudWatch metric streams: metrics stream in near real time to Firehose, which delivers them to S3 for Athena, to Redshift or to OpenSearch, or directly to third-party tools such as Datadog, Splunk and New Relic](/diagrams/mon-metric-streams.light.svg) ![CloudWatch metric streams: metrics stream in near real time to Firehose, which delivers them to S3 for Athena, to Redshift or to OpenSearch, or directly to third-party tools such as Datadog, Splunk and New Relic](/diagrams/mon-metric-streams.dark.svg)
Push metrics out continuously, instead of polling.
**[Metric streams](/docs/glossary#term-cloudwatch-metric-streams)** continually stream CloudWatch metrics to a destination of your choice, with **near-real-time delivery** and low latency: - **Amazon Data Firehose** (and then its destinations: S3, Redshift, OpenSearch…); - **third-party service providers:** Datadog, Dynatrace, New Relic, Splunk, Sumo Logic… You can **filter metrics** to stream only a subset of them. ## Real-world examples [#real-world-examples] - **An online shop** publishes `OrdersPerMinute` as a custom metric and puts it on a dashboard next to EC2 CPU and ALB latency. - **A company that uses Datadog** streams all CloudWatch metrics to it with a metric stream, instead of polling the CloudWatch API. ## Exam tips [#exam-tips] - **"Monitor RAM (memory) or disk space of EC2"** → custom metric, usually through the CloudWatch agent. - **"Metrics every second"** → high-resolution custom metrics. **"EC2 metrics every minute"** → detailed monitoring. - **"Send CloudWatch metrics to a third-party tool or S3 in near real time"** → metric streams. ## Common traps [#common-traps] - **"EC2 reports memory usage by default."** It doesn't; CPU, network, disk I/O and status checks are built in, RAM is a custom metric. - **"Metrics are kept forever."** At most 15 months. ## Hands-on lab: publish a custom metric [#hands-on-lab-publish-a-custom-metric] **Goal:** send your own metric to CloudWatch and graph it. A custom metric costs about $0.30 a month, charged by the hour, and API calls cost $0.01 per 1,000, so this lab costs **less than a cent** if you finish within a day. Any Region works. ### Publish data points [#publish-data-points] In CloudShell, run the `put-metric-data` command above three times with different values (42, 55, 37), a minute apart. ### Graph it [#graph-it] Open **CloudWatch → Metrics → All metrics → Custom namespaces → MyApp → Env**, tick **ActiveUsers**, and set the period to 1 minute. **Expected result:** a graph with your three points. **Clean up:** nothing to delete; a metric with no new data stops being billed and expires after 15 months. ## AWS documentation [#aws-documentation] - [Metrics concepts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html) - [Publish custom metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html) - [Use metric streams](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html) # AWS Config (/docs/management/config) ## What it is [#what-it-is] **[AWS Config](/docs/glossary#term-aws-config)** helps with **auditing and recording compliance** of your AWS resources. - It **records configurations and changes over time**. - Questions AWS Config can answer: - Is there unrestricted SSH access to my security groups? - Do my buckets have any public access? - How has my ALB configuration changed over time? - You can receive **alerts (SNS notifications)** for any changes. - AWS Config is a **per-Region** service. - It can be **aggregated across Regions and accounts** (an aggregator). - You can store the configuration data in **S3** (and analyse it with Athena). ## Config rules [#config-rules] - Use **AWS managed Config rules** (hundreds of them; the slides say over 75). - Make **custom Config rules**, defined in **AWS Lambda** (or with the Guard policy language): - for example, evaluate whether each EBS disk is of type gp2; - or whether each EC2 instance is a `t2.micro`. - Rules can be evaluated or triggered: - **for each configuration change**; - and/or **at regular time intervals**. - **AWS Config rules do not prevent actions from happening** (no deny). - **Pricing:** no free tier; about **$0.003 per configuration item recorded** per Region, and **$0.001 per rule evaluation** per Region. ## Config resource view [#config-resource-view] For each resource, AWS Config shows: - its **compliance over time** (compliant, non-compliant); - its **configuration over time** (each change, field by field); - the **CloudTrail API calls** made on it over time. ## Remediations [#remediations]
![AWS Config auto remediation: a Config rule finds an unused IAM access key NON_COMPLIANT and triggers an SSM Automation runbook that deactivates the key, retrying if the resource is still non-compliant](/diagrams/mon-config-remediation.light.svg) ![AWS Config auto remediation: a Config rule finds an unused IAM access key NON_COMPLIANT and triggers an SSM Automation runbook that deactivates the key, retrying if the resource is still non-compliant](/diagrams/mon-config-remediation.dark.svg)
Find the problem, then fix it automatically.
- **Automate remediation** of non-compliant resources with **SSM Automation documents**. - Use **AWS-managed Automation documents**, or create **custom** ones. Tip: a custom Automation document can invoke a Lambda function. - Set **remediation retries** if the resource is still non-compliant after auto remediation. For example, a rule finds IAM access keys older than 90 days (`NON_COMPLIANT`) and triggers the `AWSConfigRemediation-RevokeUnusedIAMUserCredentials` document, which deactivates them. ## Notifications [#notifications] - Use **EventBridge** to trigger notifications when AWS resources become **non-compliant**, and send them to Lambda, SNS, SQS… - Send **configuration changes and compliance state notifications** to **SNS** (all events; use SNS filtering, or filter on the client side), for example to email an admin. ## Real-world examples [#real-world-examples] - **A security team** uses the managed rule `restricted-ssh` to find every security group open to `0.0.0.0/0` on port 22, and an auto remediation removes the rule. - **An auditor** asks how a load balancer was configured on 3 March. The Config timeline shows its listeners, security groups and certificate on that day. ## Exam tips [#exam-tips] - **"Is this resource compliant?", "track configuration changes over time"** → AWS Config. - **"Automatically fix non-compliant resources"** → Config rule + remediation with SSM Automation. - **"Notify when a resource becomes non-compliant"** → Config + EventBridge (or SNS). - **"Compliance across accounts and Regions"** → Config aggregator. - **"Custom compliance check"** → custom Config rule with Lambda. ## Common traps [#common-traps] - **"Config prevents non-compliant changes."** It only detects (and can remediate after the fact). To prevent, use IAM policies or SCPs. - **"Config is global."** It's per Region; aggregate for one view. ## Check yourself [#check-yourself] Config charges for every configuration item it records as soon as you turn it on, so instead: An AWS Config rule (such as `s3-bucket-public-read-prohibited`) with automatic remediation through an SSM Automation document that blocks public access; Config keeps the configuration timeline. AWS Config shows each security group's compliance and configuration history, with links to the CloudTrail API calls that changed it. ## AWS documentation [#aws-documentation] - [What is AWS Config?](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html) - [Evaluating resources with AWS Config rules](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config.html) - [Remediating noncompliant resources](https://docs.aws.amazon.com/config/latest/developerguide/remediation.html) - [AWS Config pricing](https://aws.amazon.com/config/pricing/) # AWS Health Dashboard (/docs/management/health-dashboard) The AWS Health Dashboard is on the exam guide's in-scope list but not in the course slides. This page is written from the AWS documentation. ## What it is [#what-it-is] The **[AWS Health Dashboard](/docs/glossary#term-aws-health-dashboard)** tells you about **AWS-side events** that can affect your workloads. It has two views: - **Service health:** the public status of every AWS service in every Region (the old *Service Health Dashboard*). It shows general outages and is the same for everyone. - **Your account health** (formerly *Personal Health Dashboard*): **personalized** events for the resources **in your account**: - issues that affect your resources (for example, an EBS volume on degraded hardware); - **scheduled changes**, such as EC2 instance retirements, maintenance windows for RDS, or certificate and runtime end-of-life notices; - account notifications. With **AWS Organizations**, the **organizational view** shows Health events for every account in one place. ## Automating with Health events [#automating-with-health-events] - **Amazon EventBridge** receives AWS Health events (free, for every customer). A rule can react automatically: notify a Slack channel through SNS and Lambda, or restart an instance scheduled for retirement before AWS does. - The **AWS Health API** lets in-house tools read Health events (it needs a Business or Enterprise support plan). ## Real-world examples [#real-world-examples] - **An operations team** has an EventBridge rule on `AWS_EC2_INSTANCE_RETIREMENT_SCHEDULED` that opens a ticket and emails the instance owner. - **During a Regional incident**, an engineer checks *Your account health* to see whether their own resources are affected, rather than reading the general status page. ## Exam tips [#exam-tips] - **"Be notified of AWS maintenance or issues that affect resources in my account"** → AWS Health Dashboard (your account health). - **"Automatically respond to an AWS Health event"** → AWS Health events in EventBridge. - **"Health events for all accounts in the organization"** → organizational view. ## Common traps [#common-traps] - **"CloudWatch alarms tell you about AWS scheduled maintenance."** Scheduled changes come from AWS Health. ## AWS documentation [#aws-documentation] - [What is AWS Health?](https://docs.aws.amazon.com/health/latest/ug/what-is-aws-health.html) # Monitoring & Governance (/docs/management) ## Three questions, three services [#three-questions-three-services] Running workloads on AWS means answering three kinds of question: - **Monitoring:** is it healthy and fast? Is something about to break? - **Auditing:** who did what, and when? - **Compliance:** is every resource configured the way our rules say?
![CloudWatch answers how resources are performing, with metrics, logs, alarms, dashboards and events; CloudTrail answers who did what and when, recording every API call in the account; AWS Config answers what changed and whether resources are compliant, with configuration history and rules](/diagrams/mon-three-services.light.svg) ![CloudWatch answers how resources are performing, with metrics, logs, alarms, dashboards and events; CloudTrail answers who did what and when, recording every API call in the account; AWS Config answers what changed and whether resources are compliant, with configuration history and rules](/diagrams/mon-three-services.dark.svg)
Performance, activity and configuration.
- **[CloudWatch](/docs/management/cloudwatch-metrics):** - performance monitoring (metrics, CPU, network…) and dashboards; - events and alerting; - log aggregation and analysis. - **[CloudTrail](/docs/management/cloudtrail):** - records API calls made within your account by everyone; - you can define trails for specific resources; - a global service. - **[AWS Config](/docs/management/config):** - records configuration changes; - evaluates resources against compliance rules; - gives a timeline of changes and compliance. ### Example: an Elastic Load Balancer [#example-an-elastic-load-balancer] - **CloudWatch:** - monitor the incoming connections metric; - visualize error codes as a percentage over time; - build a dashboard of the load balancer's performance. - **Config:** - track the security group rules of the load balancer; - track its configuration changes; - make sure an SSL certificate is always assigned to it (a compliance rule). - **CloudTrail:** - track **who** made changes to the load balancer, with which API calls. ## In this group [#in-this-group] [EventBridge](/docs/integration/eventbridge) (formerly CloudWatch Events) is in the Application Integration group. ## Exam tips [#exam-tips] - **"Monitor performance", "metrics", "alarm when CPU is high", "logs"** → CloudWatch. - **"Who deleted the resource?", "audit API calls"** → CloudTrail. - **"Is the resource compliant?", "track configuration changes over time"** → AWS Config. ## Common traps [#common-traps] - **"CloudTrail shows CPU usage."** CloudTrail records API calls; metrics are in CloudWatch. - **"Config blocks non-compliant changes."** Config detects and reports (and can remediate); it doesn't prevent. To prevent, use IAM or SCPs. ## AWS documentation [#aws-documentation] - [What is Amazon CloudWatch?](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) - [What is AWS CloudTrail?](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) - [What is AWS Config?](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html) # Managed Grafana and Managed Service for Prometheus (/docs/management/managed-grafana-prometheus) These two services are on the exam guide's in-scope list but not in the course slides. This page is written from the AWS documentation. ## Open-source monitoring, managed [#open-source-monitoring-managed] **Prometheus** (metrics) and **Grafana** (dashboards) are popular open-source monitoring tools, especially for Kubernetes. Running them yourself means sizing servers, storage and high availability. AWS runs both as managed services.
![Amazon Managed Service for Prometheus and Amazon Managed Grafana: an EKS cluster writes container metrics to Managed Prometheus; Managed Grafana queries them with PromQL, alongside other data sources such as CloudWatch, X-Ray and OpenSearch, and the team signs in with SSO to view the dashboards](/diagrams/mon-grafana-prometheus.light.svg) ![Amazon Managed Service for Prometheus and Amazon Managed Grafana: an EKS cluster writes container metrics to Managed Prometheus; Managed Grafana queries them with PromQL, alongside other data sources such as CloudWatch, X-Ray and OpenSearch, and the team signs in with SSO to view the dashboards](/diagrams/mon-grafana-prometheus.dark.svg)
Prometheus stores metrics; Grafana shows them.
## Amazon Managed Service for Prometheus [#amazon-managed-service-for-prometheus] **[Amazon Managed Service for Prometheus](/docs/glossary#term-amazon-managed-service-for-prometheus)** is a **serverless, Prometheus-compatible monitoring service for container metrics**. - Use the same **Prometheus data model** and **PromQL** query language you already use. - **Automatically scales** ingestion, storage and queries. - **Highly available:** data is replicated across **three AZs**. - Collects metrics from **EKS**, ECS and self-managed Kubernetes (with a managed collector or your own Prometheus server writing to it). ## Amazon Managed Grafana [#amazon-managed-grafana] **[Amazon Managed Grafana](/docs/glossary#term-amazon-managed-grafana)** is a **fully managed Grafana** for querying, correlating and **visualizing metrics, logs and traces** from many sources. - You create **workspaces** (logically isolated Grafana servers); AWS handles provisioning, scaling and patching. - **Data sources:** Managed Prometheus, **CloudWatch**, **X-Ray**, **OpenSearch**, Timestream, Athena and third-party tools. - Users sign in with **IAM Identity Center** or a **SAML** identity provider. ## Real-world examples [#real-world-examples] - **A platform team** moves from self-hosted Prometheus on EC2 to Managed Prometheus for 30 EKS clusters, and builds one Grafana dashboard that also shows CloudWatch metrics for RDS. ## Exam tips [#exam-tips] - **"Prometheus-compatible", "PromQL", "monitor container metrics at scale without managing servers"** → Amazon Managed Service for Prometheus. - **"Grafana dashboards", "visualize metrics from several sources, managed"** → Amazon Managed Grafana. - **"Already use Prometheus and Grafana on premises, move to AWS with the least operational overhead"** → both managed services. ## Common traps [#common-traps] - **"Managed Grafana stores your metrics."** Grafana visualizes; Prometheus (or CloudWatch) stores the data. ## AWS documentation [#aws-documentation] - [What is Amazon Managed Service for Prometheus?](https://docs.aws.amazon.com/prometheus/latest/userguide/what-is-Amazon-Managed-Service-Prometheus.html) - [What is Amazon Managed Grafana?](https://docs.aws.amazon.com/grafana/latest/userguide/what-is-Amazon-Managed-Service-Grafana.html) # Service Catalog, Proton and License Manager (/docs/management/service-catalog-proton-license-manager) These three services are on the exam guide's in-scope list but not in the course slides. This page is written from the AWS documentation. ## AWS Service Catalog [#aws-service-catalog] **[AWS Service Catalog](/docs/glossary#term-aws-service-catalog)** lets an organization create **catalogs of IT services approved for AWS**, so users can launch what they need **on their own**, within the rules. - **Products:** CloudFormation templates (for example "approved web server", "standard VPC", "data science notebook"). - **Portfolios:** collections of products, shared with **IAM users, groups or roles**, or with other accounts (and the whole organization). - **Constraints:** limit how a product can be launched (allowed instance types, Regions, tags). A **launch constraint** gives the product an IAM role, so users can launch it **without having permissions on the underlying services**. - Users browse the catalog and launch a product as a **provisioned product**. **Use case:** developers launch a pre-approved, tagged and encrypted environment in minutes, without broad IAM permissions and without waiting for the platform team. ## AWS Proton [#aws-proton] **AWS Proton** let platform teams publish versioned templates for container and serverless applications, which developers used to deploy their services. **AWS ended support for Proton on 7 October 2026.** The console and Proton resources are no longer accessible; infrastructure that Proton deployed keeps running. The exam guide still lists Proton, but AWS replaces exam questions about features that change, so expect few or none. If one appears, the idea is "self-service templates for platform teams to standardise container and serverless deployments". ## AWS License Manager [#aws-license-manager] **[AWS License Manager](/docs/glossary#term-aws-license-manager)** manages **software licences** from vendors such as **Microsoft, SAP, Oracle and IBM** across AWS accounts and Regions, and on premises. - **BYOL (bring your own licence):** reuse licences you already own on AWS (for example with Dedicated Hosts). - **License rules:** count licences by vCPU, cores, sockets or instances, and set **hard or soft limits**. A hard limit **stops launches** that would break your licence agreement. - **Tracking and reporting:** see licence usage across the organization, for audits. **Use case:** a company with 100 Windows Server licences sets a hard limit, so an engineer can't launch a 101st licensed instance by mistake. ## Exam tips [#exam-tips] - **"Let users self-provision only approved, compliant resources", "catalog of approved products"** → AWS Service Catalog. - **"Users launch products without permissions on the underlying services"** → Service Catalog launch constraint. - **"Track software licences, BYOL, prevent licence overuse"** → AWS License Manager. ## Common traps [#common-traps] - **"Service Catalog creates the templates."** You write CloudFormation templates; Service Catalog governs who can launch them and how. ## AWS documentation [#aws-documentation] - [What is AWS Service Catalog?](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html) - [What is AWS Proton?](https://docs.aws.amazon.com/proton/latest/userguide/Welcome.html) - [What is AWS License Manager?](https://docs.aws.amazon.com/license-manager/latest/userguide/license-manager.html) # AWS Systems Manager (/docs/management/systems-manager) ## What it is [#what-it-is] **[AWS Systems Manager](/docs/glossary#term-aws-systems-manager)** (SSM) helps you manage your **EC2 instances and on-premises servers** at scale. - A server becomes a **managed node** when the **SSM Agent** is installed (it's preinstalled on Amazon Linux and many AMIs) and it has **IAM permissions** to talk to Systems Manager (an instance role with `AmazonSSMManagedInstanceCore`). - Works on **Linux, macOS and Windows**, in AWS and on premises (hybrid). - It's a family of tools; the ones below are the most important for the exam. ([Parameter Store](/docs/security/ssm-parameter-store) is covered in the Security & Encryption group.) ## Session Manager [#session-manager]
![Session Manager: a user with IAM permissions starts a session from the browser or CLI and gets a shell on an EC2 instance or on-premises server running the SSM Agent, with no SSH keys, no bastion and no inbound port 22; session logs go to S3 or CloudWatch Logs](/diagrams/mon-ssm-session.light.svg) ![Session Manager: a user with IAM permissions starts a session from the browser or CLI and gets a shell on an EC2 instance or on-premises server running the SSM Agent, with no SSH keys, no bastion and no inbound port 22; session logs go to S3 or CloudWatch Logs](/diagrams/mon-ssm-session.dark.svg)
A shell without SSH.
**[Session Manager](/docs/glossary#term-session-manager)** starts a **secure shell** on your EC2 instances and on-premises servers. - **No SSH access, bastion hosts or SSH keys needed.** - **No port 22 needed** (better security): close all inbound ports. - Supports Linux, macOS and Windows. - Access is controlled with **IAM**, and you can send **session log data to S3 or CloudWatch Logs**. You tried it in the [connecting to EC2 lab](/docs/compute/connecting-to-ec2#hands-on-lab-three-ways-in). ## Run Command [#run-command]
![Systems Manager Run Command: a maintenance window or an EventBridge rule runs a document or script on EC2 instances selected by tag and on on-premises servers with the SSM Agent; command output goes to S3 or CloudWatch Logs and status notifications to SNS](/diagrams/mon-ssm-run-command.light.svg) ![Systems Manager Run Command: a maintenance window or an EventBridge rule runs a document or script on EC2 instances selected by tag and on on-premises servers with the SSM Agent; command output goes to S3 or CloudWatch Logs and status notifications to SNS](/diagrams/mon-ssm-run-command.dark.svg)
One command, many servers, no SSH.
**[Run Command](/docs/glossary#term-run-command)**: - executes a **document** (= script) or just runs a command; - runs it **across multiple instances** (selected by tags or resource groups); - **no need for SSH**; - shows **command output** in the console, or sends it to an **S3 bucket** or **CloudWatch Logs**; - sends **notifications to SNS** about command status (in progress, success, failed…); - is **integrated with IAM and CloudTrail**; - can be **invoked by EventBridge**. ## Patch Manager [#patch-manager] **[Patch Manager](/docs/glossary#term-patch-manager)**: - **automates patching** of managed instances: OS updates, application updates, security updates; - supports **EC2 instances and on-premises servers**, on Linux, macOS and Windows; - patches **on demand** or **on a schedule** with **Maintenance Windows**; - **scans** instances and produces a **patch compliance report** (missing patches). Under the hood, it runs the `AWS-RunPatchBaseline` document through Run Command. ## Maintenance Windows [#maintenance-windows] A **maintenance window** defines a **schedule** for when to perform actions on your instances: OS patching, updating drivers, installing software… A maintenance window contains: - a **schedule** (for example every Sunday at 02:00); - a **duration**; - a set of **registered instances**; - a set of **registered tasks** (Run Command, Automation, Lambda…). ## Automation [#automation]
![Systems Manager Automation: started from the console, CLI or SDK, a maintenance window, EventBridge or an AWS Config remediation, a runbook restarts EC2 instances, creates AMIs or EBS snapshots, and acts on RDS and other resources](/diagrams/mon-ssm-automation.light.svg) ![Systems Manager Automation: started from the console, CLI or SDK, a maintenance window, EventBridge or an AWS Config remediation, a runbook restarts EC2 instances, creates AMIs or EBS snapshots, and acts on RDS and other resources](/diagrams/mon-ssm-automation.dark.svg)
Runbooks for routine operations.
**[SSM Automation](/docs/glossary#term-ssm-automation)** simplifies common **maintenance and deployment tasks** of EC2 instances and other AWS resources. - Examples: restart instances, create an AMI, take an EBS snapshot. - An **Automation runbook** is an SSM document that defines actions on your EC2 instances or AWS resources (pre-defined by AWS, such as `AWS-RestartEC2Instance`, or custom). - Can be triggered: - manually, with the AWS console, CLI or SDK; - by **EventBridge**; - on a schedule with **Maintenance Windows**; - by **AWS Config** for rule remediations. ## Real-world examples [#real-world-examples] - **A company** closes port 22 on every instance and gives engineers shell access only through Session Manager, with every session logged to S3. - **An operations team** patches 500 Windows and Linux servers every Sunday night with Patch Manager in a maintenance window, and checks the compliance report on Monday. ## Exam tips [#exam-tips] - **"Shell access without SSH, bastion hosts, keys or port 22"** → Session Manager. - **"Run a script on many instances at once"** → Run Command. - **"Patch EC2 and on-premises servers, compliance report"** → Patch Manager (+ Maintenance Windows). - **"Automate routine tasks: restart, AMI, snapshot"** → SSM Automation runbooks. - **"Instance doesn't appear in Systems Manager"** → check the SSM Agent and the instance's IAM role (and network access to SSM endpoints). ## Common traps [#common-traps] - **"Session Manager needs port 22 open."** It needs no inbound ports at all. - **"Systems Manager only works on EC2."** It also manages on-premises servers. ## Check yourself [#check-yourself] The Session Manager lab is on the connecting to EC2 page; the rest needs several instances, so instead: Use Session Manager with no inbound ports open, IAM to control who can start sessions, and session logging to S3 or CloudWatch Logs. Install the SSM Agent (hybrid activation for on premises), then use Patch Manager with a patch baseline, scheduled by a maintenance window, and read the patch compliance report. ## AWS documentation [#aws-documentation] - [What is AWS Systems Manager?](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) - [Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html) - [Run Command](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) - [Patch Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager.html) - [Maintenance Windows](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows.html) - [Automation](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation.html) # AWS X-Ray (/docs/management/x-ray) AWS X-Ray is on the exam guide's in-scope list (and named in task 2.2) but not in the course slides. This page is written from the AWS documentation. ## What it is [#what-it-is]
![AWS X-Ray: a request passes through API Gateway, Lambda and DynamoDB; API Gateway and Lambda send trace segments to X-Ray, which builds a trace map showing the time spent in each service, here revealing a slow DynamoDB call](/diagrams/mon-x-ray.light.svg) ![AWS X-Ray: a request passes through API Gateway, Lambda and DynamoDB; API Gateway and Lambda send trace segments to X-Ray, which builds a trace map showing the time spent in each service, here revealing a slow DynamoDB call](/diagrams/mon-x-ray.dark.svg)
Follow one request through every service.
**[AWS X-Ray](/docs/glossary#term-aws-x-ray)** gives **distributed tracing**: it follows each request through your application, across services, to show **where time is spent and where errors happen**. In a microservices or serverless application, one click can call API Gateway, three Lambda functions, DynamoDB and an external API. Logs show each piece separately; X-Ray connects them. - **Trace:** the whole journey of one request, with a trace ID passed along in a **tracing header**. - **Segments:** the work done by each service (host, request, response, start and end times, errors). **Subsegments** break it down further, such as a call to DynamoDB or an HTTP API. - **Trace map** (service graph): a visual map of your services and their connections, with latency and error rates on each. - **Sampling:** X-Ray records a sample of requests (for example the first request each second and 5% of the rest), to keep cost and overhead low. - **Annotations:** key-value pairs you add to traces, to search them (for example `customer_id`). **Integrations:** Lambda (turn on active tracing), API Gateway, Elastic Beanstalk, ECS, EKS, EC2, SNS, SQS, Step Functions and more. On **25 February 2026**, the **X-Ray SDKs and daemon entered maintenance mode** (security fixes only). AWS now recommends instrumenting applications with **OpenTelemetry** (for example the AWS Distro for OpenTelemetry or the CloudWatch agent), which still sends traces to X-Ray. The service itself and the exam idea are unchanged. ## Real-world examples [#real-world-examples] - **An e-commerce API** is slow at checkout. The X-Ray trace map shows 90% of the time is spent in a call from Lambda to a third-party payment API. - **A team** filters traces by the annotation `customer_id = 4711` to see exactly what happened to one customer's failed request. ## Exam tips [#exam-tips] - **"Trace requests across microservices", "find the bottleneck", "service map", "debug distributed applications"** → AWS X-Ray. - **"Troubleshoot latency in a serverless application end to end"** → X-Ray (with Lambda active tracing). ## Common traps [#common-traps] - **"CloudTrail traces application requests."** CloudTrail records AWS API calls for auditing; X-Ray traces your application's requests. - **"X-Ray records every request."** It samples them. ## Check yourself [#check-yourself] Instrument the services with X-Ray (or OpenTelemetry sending to X-Ray) and use the trace map and traces to find which downstream call adds the latency. ## AWS documentation [#aws-documentation] - [What is AWS X-Ray?](https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html) - [AWS X-Ray concepts](https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html) - [Migrating from X-Ray instrumentation to OpenTelemetry](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-migration.html) # Application Discovery Service and MGN (/docs/migration/application-discovery-mgn) ## AWS Application Discovery Service [#aws-application-discovery-service] **[AWS Application Discovery Service](/docs/glossary#term-aws-application-discovery-service)** helps you **plan migration projects** by gathering information about **on-premises data centers**. - **Server utilization data** and **dependency mapping** are important for migrations. - **Agentless discovery** (AWS Agentless Discovery Connector / Collector): VM inventory, configuration and performance history such as CPU, memory and disk usage (from VMware vCenter). - **Agent-based discovery** (AWS Application Discovery Agent): system configuration, system performance, running processes, and details of the **network connections** between systems. - Resulting data can be viewed within **AWS Migration Hub** (and exported to Athena or QuickSight). **AWS Application Discovery Service** and **AWS Migration Hub** are **no longer open to new customers** (since 7 November 2025). AWS now points new migrations to **AWS Transform**, which discovers, plans and migrates with AI agents. The exam guide still lists Application Discovery Service: the idea to remember is "collect server inventory, utilization and dependencies to plan a migration". ## AWS Application Migration Service (MGN) [#aws-application-migration-service-mgn]
![AWS Application Migration Service: a replication agent on each source server, in a data center or another cloud, continuously replicates its disks at block level to a low-cost staging area of EC2 instances and EBS volumes in AWS; at cutover, which takes minutes, MGN launches the target EC2 instances in production](/diagrams/mig-mgn.light.svg) ![AWS Application Migration Service: a replication agent on each source server, in a data center or another cloud, continuously replicates its disks at block level to a low-cost staging area of EC2 instances and EBS volumes in AWS; at cutover, which takes minutes, MGN launches the target EC2 instances in production](/diagrams/mig-mgn.dark.svg)
Replicate continuously, cut over in minutes.
**[AWS Application Migration Service](/docs/glossary#term-aws-application-migration-service)** (MGN) is the AWS evolution of **CloudEndure Migration**, and replaces **AWS Server Migration Service (SMS)**. - A **lift-and-shift (rehost)** solution that simplifies migrating applications to AWS. - Converts your **physical, virtual and cloud-based servers** to run natively on AWS. - Supports a wide range of platforms, operating systems and databases. - **Minimal downtime, reduced costs.** - How it works: 1. install the **AWS Replication Agent** on each source server; 2. it does **continuous block-level replication** to a **staging area** of low-cost EC2 instances and EBS volumes; 3. launch **test instances** to check them; 4. at **cutover** (minutes), MGN launches the **target EC2 instances and EBS volumes** in production. The current AWS documentation calls the service **AWS Transform MGN**; it's the same Application Migration Service. ## Real-world examples [#real-world-examples] - **A company** moving 300 VMware VMs uses discovery data to group servers into waves by dependency, then rehosts each wave with MGN over a weekend each. ## Exam tips [#exam-tips] - **"Plan a migration: inventory, utilization, dependencies of on-premises servers"** → Application Discovery Service (agentless for VMware inventory; agent for processes and network connections). - **"Lift and shift servers to EC2 with minimal downtime"** → Application Migration Service (MGN). - **"CloudEndure Migration" or "Server Migration Service" in an old question** → MGN. - **"Track migration progress in one place"** → Migration Hub (closed to new customers). ## Common traps [#common-traps] - **"MGN migrates databases to RDS."** It rehosts whole servers to EC2; for managed databases use DMS. - **"Agentless discovery shows network connections between servers."** That needs the agent. ## AWS documentation [#aws-documentation] - [What is AWS Application Discovery Service?](https://docs.aws.amazon.com/application-discovery/latest/userguide/what-is-appdiscovery.html) - [What is AWS Application Migration Service (Transform MGN)?](https://docs.aws.amazon.com/mgn/latest/ug/what-is-application-migration-service.html) - [What is AWS Migration Hub?](https://docs.aws.amazon.com/migrationhub/latest/ug/whatishub.html) # AWS DataSync (/docs/migration/datasync) ## What it is [#what-it-is]
![AWS DataSync: an agent next to an on-premises NFS or SMB server sends data over TLS to DataSync on a schedule, which writes it to Amazon S3 in any storage class, Amazon EFS or any Amazon FSx file system; transfers between AWS storage services need no agent](/diagrams/mig-datasync.light.svg) ![AWS DataSync: an agent next to an on-premises NFS or SMB server sends data over TLS to DataSync on a schedule, which writes it to Amazon S3 in any storage class, Amazon EFS or any Amazon FSx file system; transfers between AWS storage services need no agent](/diagrams/mig-datasync.dark.svg)
Online copy and sync, on a schedule.
**[AWS DataSync](/docs/glossary#term-aws-datasync)** moves **large amounts of data** to and from AWS, online. - **On premises or another cloud → AWS** (NFS, SMB, HDFS, object storage, other clouds' storage): **needs an agent** near the source. - **AWS → AWS** (between storage services): **no agent needed**. - Can synchronize to: - **Amazon S3** (any storage class, including Glacier); - **Amazon EFS**; - **Amazon FSx** (Windows, Lustre, NetApp ONTAP, OpenZFS). - Replication tasks can be **scheduled** hourly, daily, weekly. - **File permissions and metadata are preserved** (NFS POSIX, SMB…). - One agent task can use up to 10 Gbps; you can set a **bandwidth limit**. - Data is encrypted in transit (TLS) and verified at the end. DataSync now has an **Enhanced mode** for virtually unlimited numbers of files with higher performance; Basic mode has file-count quotas. ## Real-world examples [#real-world-examples] - **A studio** copies 80 TB of video from its NAS to S3 with DataSync over Direct Connect, then keeps a nightly sync running until cut-over. - **A team** copies an EFS file system to another Region every night with DataSync, without any agent. ## Exam tips [#exam-tips] - **"Move or sync files online from NFS/SMB to S3, EFS or FSx"** → DataSync (with an agent). - **"Copy between EFS, FSx and S3", "keep metadata and permissions"** → DataSync. - **"Scheduled transfers"** → DataSync tasks. **"Ongoing on-premises access to S3 files"** → Storage Gateway instead. ## Common traps [#common-traps] - **"DataSync needs an agent for S3 to EFS."** AWS-to-AWS transfers don't. - **"DataSync is a file share."** It copies data; it doesn't serve files to applications (that's Storage Gateway or EFS/FSx). ## Check yourself [#check-yourself] A DataSync lab needs an on-premises share or two file systems, so instead: Deploy a DataSync agent next to the NFS server, create a task from the NFS location to the EFS location, run it once, then schedule it nightly. ## AWS documentation [#aws-documentation] - [What is AWS DataSync?](https://docs.aws.amazon.com/datasync/latest/userguide/what-is-datasync.html) - [Where can I transfer my data with DataSync?](https://docs.aws.amazon.com/datasync/latest/userguide/working-with-locations.html) - [Choosing a task mode](https://docs.aws.amazon.com/datasync/latest/userguide/choosing-task-mode.html) # DMS and schema conversion (/docs/migration/dms-sct) ## AWS DMS [#aws-dms] **[AWS Database Migration Service](/docs/glossary#term-aws-dms)** (DMS) migrates databases to AWS **quickly and securely**; it's resilient and self-healing. - The **source database remains available** during the migration. - Supports: - **homogeneous** migrations: for example Oracle to Oracle; - **heterogeneous** migrations: for example Microsoft SQL Server to Aurora. - **Continuous data replication** using **CDC** (change data capture). - You create a **replication instance** (an EC2 instance managed by DMS) to perform the replication tasks. **DMS Serverless** now provisions and scales the replication capacity for you, so you don't size a replication instance. **DMS Schema Conversion** converts schemas in the console as a managed alternative to downloading SCT, and **DMS Fleet Advisor** inventories your source databases. ### Sources and targets [#sources-and-targets] **Sources:** - on-premises and EC2 databases: Oracle, MS SQL Server, MySQL, MariaDB, PostgreSQL, MongoDB, SAP, Db2; - Azure SQL Database (and other clouds' databases); - Amazon RDS, including Aurora; - Amazon S3; - DocumentDB. **Targets:** - on-premises and EC2 databases: Oracle, MS SQL Server, MySQL, MariaDB, PostgreSQL, SAP; - Amazon RDS (and Aurora); - **Redshift, DynamoDB, S3**; - OpenSearch Service; - **Kinesis Data Streams**; - Apache Kafka; - DocumentDB and Amazon Neptune; - Redis and Babelfish. ## Schema conversion (SCT) [#schema-conversion-sct] - The **[AWS Schema Conversion Tool](/docs/glossary#term-aws-schema-conversion-tool)** (SCT) **converts your database's schema from one engine to another**. - Example **OLTP:** SQL Server or Oracle → MySQL, PostgreSQL, Aurora. - Example **OLAP:** Teradata or Oracle → Amazon Redshift. - Prefer compute-intensive instances to optimize data conversions. - **You do not need SCT if you are migrating the same DB engine:** - for example, on-premises PostgreSQL → RDS PostgreSQL; - the DB engine is still PostgreSQL (RDS is just the platform). ## Continuous replication [#continuous-replication]
![Migrating with AWS DMS: the source Oracle database in the data center stays live while a DMS replication instance runs a full load and then continuous change data capture into the target Aurora MySQL database; because the engines differ, the AWS Schema Conversion Tool converts the schema first](/diagrams/mig-dms.light.svg) ![Migrating with AWS DMS: the source Oracle database in the data center stays live while a DMS replication instance runs a full load and then continuous change data capture into the target Aurora MySQL database; because the engines differ, the AWS Schema Conversion Tool converts the schema first](/diagrams/mig-dms.dark.svg)
Convert the schema once, then copy and keep in sync.
1. A server with **AWS SCT** converts the Oracle schema and creates it in the target (Aurora MySQL or RDS for MySQL). 2. The **DMS replication instance** does a **full load** of the data, then **CDC** keeps replicating ongoing changes. 3. When the target is in sync, switch the application over: minimal downtime. ## DMS Multi-AZ deployment [#dms-multi-az-deployment]
![AWS DMS Multi-AZ: DMS keeps a synchronous standby replica of the replication instance in another Availability Zone, which gives data redundancy, removes I/O freezes and reduces latency spikes](/diagrams/mig-dms-multiaz.light.svg) ![AWS DMS Multi-AZ: DMS keeps a synchronous standby replica of the replication instance in another Availability Zone, which gives data redundancy, removes I/O freezes and reduces latency spikes](/diagrams/mig-dms-multiaz.dark.svg)
A standby replication instance in another AZ.
- When **Multi-AZ** is enabled, DMS provisions and maintains a **synchronous standby replica** in a different AZ. - **Advantages:** data redundancy, eliminates I/O freezes, minimizes latency spikes. ## RDS and Aurora migrations [#rds-and-aurora-migrations] **RDS MySQL → Aurora MySQL:** - Option 1: **DB snapshot** from RDS MySQL restored as a MySQL Aurora DB. - Option 2: create an **Aurora read replica** from your RDS MySQL, and when the replication lag is 0, **promote** it as its own DB cluster (can take time and cost $). **External MySQL → Aurora MySQL:** - Option 1: use **Percona XtraBackup** to create a file backup in Amazon S3, then create an Aurora MySQL DB **from Amazon S3**. - Option 2: create an Aurora MySQL DB, then use the **mysqldump** utility to migrate MySQL into Aurora (slower than the S3 method). **RDS PostgreSQL → Aurora PostgreSQL:** the same two options (snapshot, or Aurora read replica then promote). **External PostgreSQL → Aurora PostgreSQL:** create a backup and put it in Amazon S3, then **import** it using the **`aws_s3` Aurora extension**. **Use DMS if both databases are up and running** (ongoing replication with minimal downtime). ## Real-world examples [#real-world-examples] - **A company** moves a 3 TB Oracle database to Aurora PostgreSQL: SCT converts the schema and flags stored procedures to rewrite by hand, then DMS does a full load and CDC for two weeks until cut-over on a Sunday night. ## Exam tips [#exam-tips] - **"Migrate a database with minimal downtime, source stays live"** → DMS (full load + CDC). - **"Different engines (Oracle → Aurora, SQL Server → MySQL)"** → schema conversion (SCT or DMS Schema Conversion) + DMS. - **"Same engine (PostgreSQL → RDS PostgreSQL)"** → DMS (or native tools) without SCT. - **"Teradata or Oracle data warehouse to Redshift"** → SCT + DMS. - **"RDS MySQL to Aurora"** → snapshot restore, or Aurora read replica then promote. - **"Stream database changes to Kinesis"** → DMS with Kinesis Data Streams as the target. ## Common traps [#common-traps] - **"SCT is needed for every migration."** Only when the engine changes. - **"DMS takes the source offline."** It stays available during the migration. ## Check yourself [#check-yourself] A DMS replication instance and two databases cost money per hour, so instead: Convert the schema with AWS SCT (or DMS Schema Conversion), then run a DMS task with full load and ongoing replication (CDC); cut over when the target has caught up. ## AWS documentation [#aws-documentation] - [What is AWS Database Migration Service?](https://docs.aws.amazon.com/dms/latest/userguide/Welcome.html) - [Sources for AWS DMS](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Introduction.Sources.html) - [Targets for AWS DMS](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Introduction.Targets.html) - [AWS DMS Serverless](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Serverless.html) - [What is the AWS Schema Conversion Tool?](https://docs.aws.amazon.com/SchemaConversionTool/latest/userguide/CHAP_Welcome.html) - [Migrating data to Aurora MySQL](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Migrating.html) - [Migrating data to Aurora PostgreSQL](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Migrating.html) # Migration & Transfer (/docs/migration) ## The 7 Rs of migration [#the-7-rs-of-migration] The 7 Rs are on the exam guide's list of migration topics but not in the course slides. This section is written from AWS Prescriptive Guidance.
![The 7 Rs of migration: retire (turn it off), retain (keep it on premises), rehost (lift and shift, for example with Application Migration Service), relocate (move VMware workloads as they are), repurchase (move to a SaaS product), replatform (lift, tinker and shift) and refactor (re-architect to be cloud native), from least effort to most change](/diagrams/mig-7rs.light.svg) ![The 7 Rs of migration: retire (turn it off), retain (keep it on premises), rehost (lift and shift, for example with Application Migration Service), relocate (move VMware workloads as they are), repurchase (move to a SaaS product), replatform (lift, tinker and shift) and refactor (re-architect to be cloud native), from least effort to most change](/diagrams/mig-7rs.dark.svg)
Seven ways to handle each application.
A **[migration strategy](/docs/glossary#term-7-rs)** is how you move one workload to AWS. AWS names seven, the **7 Rs**: - **Retire:** decommission applications nobody needs any more (for example "zombie" servers under 5% CPU). Saves money and reduces risk. - **Retain:** keep the application where it is, for now (recently upgraded, compliance, not worth moving yet). - **Rehost** ("lift and shift"): move servers as they are to EC2, usually with **[Application Migration Service](/docs/migration/application-discovery-mgn#aws-application-migration-service-mgn)**. Fastest for large migrations. - **Relocate:** move a whole platform without changing it, for example VMware workloads to **[VMware Cloud on AWS](/docs/compute/hybrid-edge-compute#vmware-cloud-on-aws)**, or containers to EKS. - **Repurchase** ("drop and shop"): replace the application with a SaaS product, for example a self-hosted CRM with Salesforce. - **Replatform** ("lift, tinker and shift"): a few optimizations without changing the core architecture, for example moving the database to **RDS** or the app to Elastic Beanstalk. - **Refactor / re-architect:** rebuild for the cloud (serverless, microservices). Most effort and most benefit; usually done **after** the migration. ## On-premises strategy with AWS [#on-premises-strategy-with-aws] - You can download **Amazon Linux 2** as a VM image (`.iso` format) to run on VMware, KVM, VirtualBox (Oracle VM) or Microsoft Hyper-V. - **[VM Import/Export](/docs/glossary#term-vm-import-export):** - migrate existing applications into EC2; - create a **DR repository** strategy for your on-premises VMs; - you can **export** the VMs back from EC2 to on premises. - **AWS Application Discovery Service:** gathers information about your on-premises servers to plan a migration (server utilization and dependency mappings). - **AWS Database Migration Service (DMS):** replicate on premises → AWS, AWS → AWS, AWS → on premises; works with many database technologies. - **AWS Application Migration Service (MGN):** incremental replication of on-premises live servers to AWS. ## Which service for which question [#which-service-for-which-question] - **Petabytes of data, slow or no network** → [Snowball Edge](/docs/migration/snow-family) (closed to new customers; see the page). - **On-premises apps use cloud storage through file, block or tape interfaces** → [Storage Gateway](/docs/migration/storage-gateway). - **Partners send files over SFTP, FTPS, FTP or AS2 into S3 or EFS** → [Transfer Family](/docs/migration/transfer-family). - **Copy or sync files online, on a schedule, keeping metadata** → [DataSync](/docs/migration/datasync). - **Move a database with minimal downtime** → [DMS](/docs/migration/dms-sct) (+ schema conversion for different engines). - **Lift and shift servers** → [Application Migration Service](/docs/migration/application-discovery-mgn). - **How long will a big transfer take?** → [transferring large amounts of data](/docs/migration/large-data-transfer). ## In this group [#in-this-group] ## Exam tips [#exam-tips] - **"Lift and shift", "least effort", "as is"** → rehost (MGN). - **"Move to a managed database during migration"** → replatform (RDS, Aurora). - **"Replace with SaaS"** → repurchase. **"Rebuild as serverless"** → refactor. ## AWS documentation [#aws-documentation] - [About the migration strategies (the 7 Rs)](https://docs.aws.amazon.com/prescriptive-guidance/latest/large-migration-guide/migration-strategies.html) - [What is VM Import/Export?](https://docs.aws.amazon.com/vm-import/latest/userguide/what-is-vmimport.html) # Transferring large amounts of data (/docs/migration/large-data-transfer) ## Worked example: 200 TB [#worked-example-200-tb]
![Moving 200 TB into AWS: over a 100 Mbps internet connection it takes about 185 days; over a 1 Gbps Direct Connect about 18.5 days, plus more than a month to set up the connection; with Snowball about one week end to end](/diagrams/mig-large-transfer.light.svg) ![Moving 200 TB into AWS: over a 100 Mbps internet connection it takes about 185 days; over a 1 Gbps Direct Connect about 18.5 days, plus more than a month to set up the connection; with Snowball about one week end to end](/diagrams/mig-large-transfer.dark.svg)
Do the maths before choosing.
**Example:** transfer **200 TB** of data into the cloud. We have a **100 Mbps** internet connection. - **Over the internet / Site-to-Site VPN:** - immediate to set up; - takes 200 (TB) × 1,000 (GB) × 1,000 (MB) × 8 (Mb) / 100 Mbps = 16,000,000 s ≈ **185 days**. - **Over Direct Connect 1 Gbps:** - long for the one-time setup (**over a month**); - takes 200 (TB) × 1,000 (GB) × 8 (Gb) / 1 Gbps = 1,600,000 s ≈ **18.5 days**. - **Over Snowball:** - takes about **1 week** for the end-to-end transfer; - can be combined with **DMS** (the bulk goes by device, changes by network). - **For ongoing replication / transfers:** Site-to-Site VPN or Direct Connect, with **DMS** or **DataSync**. The formula: **seconds = size in bits ÷ bandwidth in bits per second**. Remember the **8** (bytes to bits). Snowball is no longer available to new customers (see [Snowball Edge](/docs/migration/snow-family)). For physical transfers today, AWS points to the **AWS Data Transfer Terminal** or partners. Exam questions may still give Snowball as the answer for "hundreds of TB, slow network, one-off". ## Exam tips [#exam-tips] - **"Hundreds of TB, slow link, needed in weeks"** → Snowball (offline). - **"Quick setup, small amounts"** → internet / Site-to-Site VPN. - **"Ongoing, consistent, high bandwidth"** → Direct Connect (plus DataSync or DMS). ## Common traps [#common-traps] - **"Direct Connect for an urgent one-time transfer."** Setup takes over a month. ## Check yourself [#check-yourself] 50 × 1,000 × 8 Gb ÷ 1 Gbps = 400,000 seconds ≈ 4.6 days (in practice longer, as you rarely get full speed). ## AWS documentation [#aws-documentation] - [AWS DataSync](https://docs.aws.amazon.com/datasync/latest/userguide/what-is-datasync.html) - [What is Direct Connect?](https://docs.aws.amazon.com/directconnect/latest/UserGuide/Welcome.html) # AWS Snowball Edge (/docs/migration/snow-family) **AWS Snowball Edge is no longer available to new customers**, and AWS ends support for Snowball devices in commercial Regions on **31 December 2026**. For new projects AWS points to **DataSync** for online transfers, the **AWS Data Transfer Terminal** (sites where you bring your own storage to upload at high speed) for physical transfers, and **AWS Outposts** for edge computing. The exam guide still lists the Snow Family, so learn the ideas below: questions are about "move petabytes with a slow or no network" and "compute in a disconnected location". ## What it is [#what-it-is] **[AWS Snowball Edge](/docs/glossary#term-aws-snowball-edge)** is a family of **highly secure, portable devices** to **collect and process data at the edge**, and **migrate data into and out of AWS**. - Helps migrate up to **petabytes** of data (order several devices). - **Snowball Edge Storage Optimized:** 104 vCPUs, 416 GB memory, **210 TB** of SSD storage. - **Snowball Edge Compute Optimized:** 104 vCPUs, 416 GB memory, **28 TB** of NVMe storage, for edge computing. ## Data migrations with Snowball [#data-migrations-with-snowball]
![Moving data with Snowball: a direct upload goes over the internet and can take days to years for large amounts; with Snowball, you copy the data onto the device on site, ship it to AWS, and AWS imports it into Amazon S3](/diagrams/mig-snowball.light.svg) ![Moving data with Snowball: a direct upload goes over the internet and can take days to years for large amounts; with Snowball, you copy the data onto the device on site, ship it to AWS, and AWS imports it into Amazon S3](/diagrams/mig-snowball.dark.svg)
Sometimes a truck is faster than the network.
Time to transfer over the network: - **10 TB:** 12 days at 100 Mbps, 30 hours at 1 Gbps, 3 hours at 10 Gbps. - **100 TB:** 124 days at 100 Mbps, 12 days at 1 Gbps, 30 hours at 10 Gbps. - **1 PB:** 3 years at 100 Mbps, 124 days at 1 Gbps, 12 days at 10 Gbps. **Challenges** of network transfers: limited connectivity, limited bandwidth, high network cost, shared bandwidth (you can't use the whole line), connection stability. **AWS Snowball: offline devices to perform data migrations.** If it takes **more than a week** to transfer over the network, use Snowball devices. ## Edge computing [#edge-computing] - **Process data while it's being created at an edge location:** a truck on the road, a ship at sea, a mining station underground… - These locations may have **limited internet** and **no access to computing power**. - You set up a **Snowball Edge** device to do edge computing: - Snowball Edge Compute Optimized (dedicated to that use case) and Storage Optimized; - run **EC2 instances** or **Lambda functions** at the edge. - **Use cases:** preprocess data, machine learning, transcoding media. ## Snowball into Glacier [#snowball-into-glacier]
![Snowball into Glacier: Snowball can't import into Glacier directly, so data is imported into Amazon S3 first, and an S3 lifecycle rule moves it to an S3 Glacier storage class](/diagrams/mig-snowball-glacier.light.svg) ![Snowball into Glacier: Snowball can't import into Glacier directly, so data is imported into Amazon S3 first, and an S3 lifecycle rule moves it to an S3 Glacier storage class](/diagrams/mig-snowball-glacier.dark.svg)
Through S3 first, then a lifecycle rule.
- **Snowball can't import to Glacier directly.** - You must use **Amazon S3 first**, in combination with an **[S3 lifecycle rule](/docs/s3/lifecycle-rules)**. ## Exam tips [#exam-tips] - **"Petabytes", "limited bandwidth", "would take weeks over the network"** → Snowball Edge. - **"Compute in a remote location with no internet"** → Snowball Edge Compute Optimized (today: Outposts). - **"Snowball into Glacier"** → import into S3, then a lifecycle rule to Glacier. ## Common traps [#common-traps] - **"Snowball imports straight into Glacier."** It goes to S3 first. - **"Snowball for ongoing, continuous replication."** It's a one-off physical transfer; for ongoing use DataSync, DMS, VPN or Direct Connect. ## AWS documentation [#aws-documentation] - [What is Snowball Edge?](https://docs.aws.amazon.com/snowball/latest/developer-guide/whatisedge.html) - [Snowball Edge device specifications](https://docs.aws.amazon.com/snowball/latest/developer-guide/device-differences.html) - [AWS Snowball](https://aws.amazon.com/snowball/) # AWS Storage Gateway (/docs/migration/storage-gateway) ## Hybrid cloud for storage [#hybrid-cloud-for-storage] - AWS is pushing for **"hybrid cloud"**: part of your infrastructure is in the cloud, part is on premises. - This can be due to long cloud migrations, security requirements, compliance requirements, or IT strategy. - S3 is a proprietary storage technology (unlike EFS / NFS), so **how do you expose S3 data on premises?** With **AWS Storage Gateway**. AWS storage cloud-native options: **block** (EBS, EC2 instance store), **file** (EFS, FSx) and **object** (S3, Glacier). ## AWS Storage Gateway [#aws-storage-gateway]
![AWS Storage Gateway: on premises, file shares use the File Gateway over NFS or SMB, application servers use the Volume Gateway over iSCSI, and backup applications use the Tape Gateway as an iSCSI virtual tape library; Storage Gateway stores the data in S3 buckets, in S3 with EBS snapshots, or in S3 and Glacier for archived tapes](/diagrams/mig-storage-gateway.light.svg) ![AWS Storage Gateway: on premises, file shares use the File Gateway over NFS or SMB, application servers use the Volume Gateway over iSCSI, and backup applications use the Tape Gateway as an iSCSI virtual tape library; Storage Gateway stores the data in S3 buckets, in S3 with EBS snapshots, or in S3 and Glacier for archived tapes](/diagrams/mig-storage-gateway.dark.svg)
Three gateways, one bridge to AWS storage.
**[AWS Storage Gateway](/docs/glossary#term-aws-storage-gateway)** is a **bridge between on-premises data and cloud data**. - **Use cases:** - disaster recovery; - backup and restore; - tiered storage; - on-premises cache and low-latency file access. - **Types of Storage Gateway:** - **S3 File Gateway**; - **Volume Gateway**; - **Tape Gateway**. - Traffic is **encrypted in transit**, over the internet or Direct Connect. - **Deployment options:** a VM on premises (**VMware, Hyper-V, KVM**), an EC2 instance, or a hardware appliance. **Amazon FSx File Gateway** (on-premises access to FSx for Windows File Server shares) is **no longer available to new customers**. The S3 File Gateway, Volume Gateway and Tape Gateway remain. ## Amazon S3 File Gateway [#amazon-s3-file-gateway]
![Amazon S3 File Gateway: an on-premises application server reads and writes files over NFS or SMB to the File Gateway, which caches recently used data locally and stores the files as objects in S3 over HTTPS; a lifecycle rule can move them to Glacier](/diagrams/mig-s3-file-gateway.light.svg) ![Amazon S3 File Gateway: an on-premises application server reads and writes files over NFS or SMB to the File Gateway, which caches recently used data locally and stores the files as objects in S3 over HTTPS; a lifecycle rule can move them to Glacier](/diagrams/mig-s3-file-gateway.dark.svg)
Files on premises, objects in S3.
- Configured S3 buckets are accessible using the **NFS and SMB** protocols. - **Most recently used data is cached** in the file gateway. - Supports **S3 Standard, S3 Standard-IA, S3 One Zone-IA, S3 Intelligent-Tiering**. - **Transition to S3 Glacier using a lifecycle rule.** - Bucket access using **IAM roles** for each file gateway. - The **SMB** protocol integrates with **Active Directory (AD)** for user authentication. ## Volume Gateway [#volume-gateway] - **Block storage** using the **iSCSI** protocol, backed by S3. - Backed by **EBS snapshots**, which can help restore on-premises volumes. - **Cached volumes:** low-latency access to the **most recent data**; the full data set lives in S3. - **Stored volumes:** the **entire dataset is on premises**, with scheduled backups to S3. ## Tape Gateway [#tape-gateway] - Some companies have backup processes using **physical tapes** (!). - With Tape Gateway, companies use the **same processes, but in the cloud**. - **Virtual Tape Library (VTL)** backed by **S3 and Glacier** (Flexible Retrieval or Deep Archive for archived tapes). - Back up data using **existing tape-based processes** (and the iSCSI interface). - Works with leading **backup software** vendors. ## Real-world examples [#real-world-examples] - **A media company** keeps working with files on its office NAS, but the S3 File Gateway stores everything in S3 and lifecycle rules archive old projects to Glacier. - **A bank** replaces its tape robot with Tape Gateway; its backup software still "writes tapes", which end up in S3 Glacier Deep Archive. ## Exam tips [#exam-tips] - **"On-premises access to S3 over NFS or SMB", "local cache"** → S3 File Gateway. - **"iSCSI block storage backed by S3"** → Volume Gateway; **"low latency for recent data"** → cached volumes; **"whole dataset on premises, backed up to S3"** → stored volumes. - **"Replace physical tapes, keep the backup software"** → Tape Gateway. - **"No on-premises virtualization to run the gateway"** → hardware appliance. ## Common traps [#common-traps] - **"Storage Gateway moves data once."** It's an ongoing hybrid bridge; for one-off transfers use DataSync or Snowball. - **"Stored volumes keep only recent data locally."** That's cached volumes; stored volumes keep everything locally. ## AWS documentation [#aws-documentation] - [What is Amazon S3 File Gateway?](https://docs.aws.amazon.com/filegateway/latest/files3/what-is-file-s3.html) - [What is Volume Gateway?](https://docs.aws.amazon.com/storagegateway/latest/vgw/WhatIsStorageGateway.html) - [What is Tape Gateway?](https://docs.aws.amazon.com/storagegateway/latest/tgw/WhatIsStorageGateway.html) - [Amazon FSx File Gateway availability](https://docs.aws.amazon.com/filegateway/latest/filefsxw/what-is-file-fsxw.html) # AWS Transfer Family (/docs/migration/transfer-family) ## What it is [#what-it-is]
![AWS Transfer Family: partners with FTP clients connect to a managed SFTP, FTPS, FTP (inside a VPC only) or AS2 endpoint; users are authenticated by the service or by Active Directory, LDAP, Okta or a custom provider, and files are stored in Amazon S3 or Amazon EFS through an IAM role](/diagrams/mig-transfer-family.light.svg) ![AWS Transfer Family: partners with FTP clients connect to a managed SFTP, FTPS, FTP (inside a VPC only) or AS2 endpoint; users are authenticated by the service or by Active Directory, LDAP, Okta or a custom provider, and files are stored in Amazon S3 or Amazon EFS through an IAM role](/diagrams/mig-transfer-family.dark.svg)
Classic file transfer protocols, cloud storage behind them.
**[AWS Transfer Family](/docs/glossary#term-aws-transfer-family)** is a fully managed service for **file transfers into and out of Amazon S3 or Amazon EFS** using FTP-style protocols. - **Supported protocols:** - **AWS Transfer for FTP** (File Transfer Protocol), only within a VPC; - **AWS Transfer for FTPS** (FTP over SSL); - **AWS Transfer for SFTP** (Secure File Transfer Protocol); - **AS2** (for business-to-business EDI) and browser-based **web apps** (newer than the slides). - **Managed infrastructure:** scalable, reliable, highly available (Multi-AZ). - **Pay per provisioned endpoint per hour + data transfers in GB.** - Store and manage **users' credentials** within the service. - Integrate with **existing authentication systems:** Microsoft Active Directory, LDAP, Okta, Amazon Cognito, custom (a Lambda function). - Files land in S3 or EFS through an **IAM role**; use **Route 53** for your own domain name. - **Usage:** sharing files, public datasets, CRM, ERP… ## Real-world examples [#real-world-examples] - **A retailer** receives daily inventory files from 200 suppliers who only support SFTP. A Transfer Family SFTP endpoint writes them into an S3 bucket, where an S3 event starts processing. ## Exam tips [#exam-tips] - **"Partners send files over SFTP / FTPS / FTP into S3 or EFS, no servers to manage"** → Transfer Family. - **"Keep existing FTP clients and scripts"** → Transfer Family. ## Common traps [#common-traps] - **"Public FTP endpoint."** Plain FTP (unencrypted) is only available inside a VPC; use SFTP or FTPS over the internet. ## Check yourself [#check-yourself] A Transfer Family endpoint costs about $0.30 an hour, so instead: Replace it with an AWS Transfer Family SFTP endpoint backed by the S3 bucket, with the partners' credentials stored in the service (or a custom identity provider), and point the existing DNS name at it with Route 53. ## AWS documentation [#aws-documentation] - [What is AWS Transfer Family?](https://docs.aws.amazon.com/transfer/latest/userguide/what-is-aws-transfer-family.html) # Machine Learning (/docs/ml) ## Ready-made AI vs your own models [#ready-made-ai-vs-your-own-models] AWS machine learning comes in two layers: - **AI services:** pre-trained models behind a simple API. You send an image, a document, audio or text and get an answer back, with **no ML expertise**. Most of the exam's ML questions are about these. - **Build your own:** **SageMaker AI**, for data scientists who build, train and deploy their own models. For the SAA-C03 exam, you mostly need to **match the use case to the service**.
![AWS machine learning services: Rekognition for images and video, Textract for documents, Transcribe for speech to text, Polly for text to speech, Translate for translation, Comprehend for natural language processing, Lex and Connect for chatbots and contact centers, Kendra for document search, SageMaker AI to build your own models, and Personalize for recommendations](/diagrams/ml-services-map.light.svg) ![AWS machine learning services: Rekognition for images and video, Textract for documents, Transcribe for speech to text, Polly for text to speech, Translate for translation, Comprehend for natural language processing, Lex and Connect for chatbots and contact centers, Kendra for document search, SageMaker AI to build your own models, and Personalize for recommendations](/diagrams/ml-services-map.dark.svg)
One service per kind of input.
## Summary [#summary] - **[Rekognition](/docs/ml/vision-documents#amazon-rekognition):** face detection, labelling, celebrity recognition, content moderation. - **[Transcribe](/docs/ml/speech-language#amazon-transcribe):** audio to text (for example subtitles). - **[Polly](/docs/ml/speech-language#amazon-polly):** text to audio. - **[Translate](/docs/ml/speech-language#amazon-translate):** translations. - **[Lex](/docs/ml/lex-connect-kendra#amazon-lex):** build conversational bots (chatbots). - **[Connect](/docs/ml/lex-connect-kendra#amazon-connect):** cloud contact center. - **[Comprehend](/docs/ml/speech-language#amazon-comprehend):** natural language processing. - **[SageMaker AI](/docs/ml/sagemaker-personalize#amazon-sagemaker-ai):** machine learning for every developer and data scientist. - **[Kendra](/docs/ml/lex-connect-kendra#amazon-kendra):** ML-powered search engine. - **[Personalize](/docs/ml/sagemaker-personalize#amazon-personalize):** real-time personalized recommendations. - **[Textract](/docs/ml/vision-documents#amazon-textract):** detect text and data in documents. The exam guide's in-scope ML services are **Comprehend, Lex, Polly, Rekognition, SageMaker AI, Textract, Transcribe and Translate**. **Kendra** and **Connect** aren't on the current list, and **Personalize** is on the out-of-scope list. They're still covered here, because they appear in the course and help you rule out wrong answers. ## In this group [#in-this-group] ## Exam tips [#exam-tips] - **"Detect objects, faces, unsafe content in images or video"** → Rekognition. - **"Extract text, forms, tables from scanned documents"** → Textract. - **"Speech to text", "subtitles", "call transcripts"** → Transcribe. **"Text to speech", "app that talks"** → Polly. - **"Translate content for international users"** → Translate. - **"Sentiment", "key phrases", "entities in text"** → Comprehend; **"clinical text", "PHI"** → Comprehend Medical. - **"Chatbot"** → Lex. **"Call center"** → Connect. - **"Build, train and deploy custom ML models"** → SageMaker AI. ## Common traps [#common-traps] - **"Rekognition for text in scanned forms."** Rekognition finds text in photos; Textract extracts structured data (forms, tables) from documents. - **"Comprehend translates text."** Comprehend analyses text; Translate translates it. - **"Use SageMaker AI to add image labelling to an app."** A pre-trained AI service (Rekognition) needs no model building. ## AWS documentation [#aws-documentation] - [Machine learning on AWS](https://aws.amazon.com/ai/machine-learning/) - [SAA-C03 in-scope services](https://docs.aws.amazon.com/aws-certification/latest/solutions-architect-associate-03/saa-03-in-scope-services.html) # Lex, Connect and Kendra (/docs/ml/lex-connect-kendra) ## Amazon Lex [#amazon-lex] **[Amazon Lex](/docs/glossary#term-amazon-lex)** builds **conversational interfaces**, with the same technology that powers **Alexa**. - **Automatic speech recognition (ASR)** to convert speech to text. - **Natural language understanding (NLU)** to recognise the **intent** of text or callers ("book a hotel", "check my balance") and the details (**slots**: dates, city…). - Helps build **chatbots** and **call center bots**, for voice and text. - Integrates with **Lambda** for business logic, and with **Connect**. ## Amazon Connect [#amazon-connect] **[Amazon Connect](/docs/glossary#term-amazon-connect)** is a **cloud-based virtual contact center**. - Receive calls, create **contact flows** (call routing, menus), chat and messaging. - Can **integrate with other CRM systems** or AWS. - **No upfront payments**, about 80% cheaper than traditional contact center solutions (pay per use). The contact center product is now called **Amazon Connect Customer**, and "Amazon Connect" names a wider family of AI solutions. Exam questions still say Amazon Connect. ## Lex and Connect together [#lex-and-connect-together]
![Amazon Lex and Connect: a customer phones to book an appointment; Connect answers the call and streams it to a Lex bot, which recognizes the intent and invokes a Lambda function that schedules the appointment in the CRM](/diagrams/ml-lex-connect.light.svg) ![Amazon Lex and Connect: a customer phones to book an appointment; Connect answers the call and streams it to a Lex bot, which recognizes the intent and invokes a Lambda function that schedules the appointment in the CRM](/diagrams/ml-lex-connect.dark.svg)
A phone line that books appointments by itself.
1. A customer **calls** to schedule an appointment. 2. **Connect** answers and **streams** the call to **Lex**. 3. Lex **recognises the intent** ("book an appointment") and the date and time. 4. Lex **invokes a Lambda function**, which **schedules** the appointment in the **CRM**. ## Amazon Kendra [#amazon-kendra] Amazon Kendra and Amazon Connect aren't on the current exam guide's in-scope list. Kendra was on an older version. Know what they do so you can recognise them as answers.
![Amazon Kendra: documents from S3, RDS, SharePoint, Google Drive, OneDrive, Salesforce, ServiceNow and custom sources are indexed by Kendra; an employee asks a question in natural language, such as where the IT desk is, and Kendra answers 1st floor](/diagrams/ml-kendra.light.svg) ![Amazon Kendra: documents from S3, RDS, SharePoint, Google Drive, OneDrive, Salesforce, ServiceNow and custom sources are indexed by Kendra; an employee asks a question in natural language, such as where the IT desk is, and Kendra answers 1st floor](/diagrams/ml-kendra.dark.svg)
Ask in plain language, get the answer, not just a link.
**[Amazon Kendra](/docs/glossary#term-amazon-kendra)** is a fully managed **document search service** powered by machine learning. - **Extracts answers** from within a document (text, PDF, HTML, PowerPoint, Word, FAQs…). - **Natural language search:** "Where is the IT support desk?" → "1st floor". - **Connectors** index S3, RDS, SharePoint, Google Drive, OneDrive, Salesforce, ServiceNow and more. - **Learns from user interactions and feedback** to promote preferred results (**incremental learning**). - You can **fine-tune** search results (importance of data, freshness, custom rules). - A **GenAI index** also feeds generative AI assistants (retrieval augmented generation). ## Real-world examples [#real-world-examples] - **A bank** puts a Lex bot on its phone line through Connect, so customers can check balances without waiting for an agent. - **A company intranet** uses Kendra so staff can ask "How many days of parental leave do I get?" and get the answer from the HR policy PDF. ## Exam tips [#exam-tips] - **"Chatbot", "voice bot", "conversational interface"** → Lex. - **"Cloud contact center", "call center"** → Connect (with Lex for self-service). - **"Search documents with natural language questions"** → Kendra. ## Common traps [#common-traps] - **"Lex is a contact center."** Lex is the bot; Connect is the contact center. - **"Kendra for searching database fields."** Kendra searches documents for answers; for search on application data, use OpenSearch. ## Check yourself [#check-yourself] A Lex bot with Connect needs a claimed phone number, and Kendra charges from about $1 an hour per index, so instead: Amazon Connect for the phone line, a Lex bot to understand the request (intent and time slot), and a Lambda function that writes the appointment to the booking system. ## AWS documentation [#aws-documentation] - [What is Amazon Lex V2?](https://docs.aws.amazon.com/lexv2/latest/dg/what-is.html) - [What is Amazon Connect Customer?](https://docs.aws.amazon.com/connect/latest/adminguide/what-is-amazon-connect.html) - [What is Amazon Kendra?](https://docs.aws.amazon.com/kendra/latest/dg/what-is-kendra.html) # SageMaker AI and Personalize (/docs/ml/sagemaker-personalize) ## Amazon SageMaker AI [#amazon-sagemaker-ai] **[Amazon SageMaker AI](/docs/glossary#term-amazon-sagemaker-ai)** is a **fully managed service for developers and data scientists to build ML models**. - Doing every step in one place, and provisioning servers for each, is typically difficult. SageMaker AI does it for you: notebooks, data labelling, built-in algorithms, **training**, **tuning**, and **deployment** to hosted endpoints. - Use it when no pre-trained AI service fits and you need **your own model** trained on your data. Amazon SageMaker was renamed **Amazon SageMaker AI** in December 2024 (the slides already use the new name). "Amazon SageMaker" now names a wider platform that brings data, analytics and AI together. For the exam, SageMaker AI is the service that builds, trains and deploys models. ### The machine learning process (simplified) [#the-machine-learning-process-simplified]
![The machine learning process in SageMaker AI: historical data such as hours studied and years of AWS experience is labelled with each real exam score, then used to build, train and tune a model; the deployed model endpoint receives a new candidate's data and predicts a pass with 906](/diagrams/ml-sagemaker.light.svg) ![The machine learning process in SageMaker AI: historical data such as hours studied and years of AWS experience is labelled with each real exam score, then used to build, train and tune a model; the deployed model endpoint receives a new candidate's data and predicts a pass with 906](/diagrams/ml-sagemaker.dark.svg)
Predicting your exam score.
1. **Historical data:** for past candidates, years of IT experience, years of AWS experience, time spent on the course… 2. **Label** it with each candidate's real score (670, 890, 934…). 3. **Build, train and tune** an ML model on the labelled data. 4. **Deploy** the model. 5. **Apply** it to **new data** (you) to get a **prediction**: "pass with 906". ## Amazon Personalize [#amazon-personalize] Amazon Personalize is on the exam guide's **out-of-scope** list. Read this only to recognise it as a wrong answer. **[Amazon Personalize](/docs/glossary#term-amazon-personalize)** is a fully managed ML service to build apps with **real-time personalized recommendations**. - Examples: personalized product recommendations and re-ranking, customized direct marketing. A user bought gardening tools: recommend the next one to buy. - The **same technology used by Amazon.com**. - Reads data from **S3** and real-time events from the **Personalize API**. - Integrates into existing websites, applications, SMS and email marketing systems. - **Implement in days, not months** (you don't build, train and deploy ML yourself). - **Use cases:** retail stores, media and entertainment. ## Real-world examples [#real-world-examples] - **An insurer** trains a fraud-detection model on years of claims in SageMaker AI and calls its endpoint for every new claim. - **A streaming service** uses Personalize for its "Because you watched…" row. ## Exam tips [#exam-tips] - **"Build, train and deploy custom ML models", "data scientists"** → SageMaker AI. - **"Recommendations"** → Personalize (out of scope, but recognise it). - **"Least effort"** with an AI service that fits (Rekognition, Comprehend…) beats building a model in SageMaker AI. ## Common traps [#common-traps] - **"SageMaker AI for any ML need."** If a pre-trained AI service does the job, use it; SageMaker AI is for custom models. ## Check yourself [#check-yourself] Training and hosting a model costs money per instance-hour, so instead: Build, train and deploy a custom model with Amazon SageMaker AI: no pre-trained AI service predicts churn from a company's own data. ## AWS documentation [#aws-documentation] - [What is Amazon SageMaker AI?](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html) - [What is Amazon Personalize?](https://docs.aws.amazon.com/personalize/latest/dg/what-is-personalize.html) # Transcribe, Polly, Translate and Comprehend (/docs/ml/speech-language)
![A speech translation chain: Transcribe turns a caller's Spanish speech into text, Translate turns the Spanish text into English, and Polly reads the English text aloud for the agent](/diagrams/ml-speech-chain.light.svg) ![A speech translation chain: Transcribe turns a caller's Spanish speech into text, Translate turns the Spanish text into English, and Polly reads the English text aloud for the agent](/diagrams/ml-speech-chain.dark.svg)
Three services chained to translate a call.
## Amazon Transcribe [#amazon-transcribe] **[Amazon Transcribe](/docs/glossary#term-amazon-transcribe)** **automatically converts speech to text**. - Uses a deep learning process called **automatic speech recognition (ASR)** to convert speech to text quickly and accurately. - **Batch** (audio files in S3) or **streaming** (real time). - **Automatically removes personally identifiable information (PII)** using **redaction**. - Supports **automatic language identification** for multi-lingual audio. - Also: custom vocabularies, identifying different speakers, **Call Analytics** for contact centers, and **Transcribe Medical**. **Use cases:** - transcribe customer service calls; - automate closed captioning and subtitling; - generate metadata for media assets to create a fully searchable archive. ## Amazon Polly [#amazon-polly] **[Amazon Polly](/docs/glossary#term-amazon-polly)** **turns text into lifelike speech** using deep learning, so you can create **applications that talk**. It offers several voice engines (standard, neural, long-form, generative). ### Lexicons and SSML [#lexicons-and-ssml] - **Pronunciation lexicons** customise how words are pronounced: - stylized words: `St3ph4ne` → "Stephane"; - acronyms: `AWS` → "Amazon Web Services". - Upload the lexicons and use them in the **`SynthesizeSpeech`** operation. - **SSML (Speech Synthesis Markup Language)** lets you mark up a document for more control: - emphasizing specific words or phrases; - using phonetic pronunciation; - including breathing sounds and whispering; - using the **Newscaster** speaking style. ```xml Hello, I am very happy to meet you. This part is a secret. ``` ## Amazon Translate [#amazon-translate] **[Amazon Translate](/docs/glossary#term-amazon-translate)** gives **natural and accurate language translation**. - **Localize content**, such as websites and applications, for **international users**. - Translate **large volumes of text** efficiently, in real time or in batches. - **Custom terminology** keeps brand names and technical terms translated your way. ## Amazon Comprehend [#amazon-comprehend] **[Amazon Comprehend](/docs/glossary#term-amazon-comprehend)** is for **natural language processing (NLP)**: fully managed and serverless. It uses machine learning to find **insights and relationships in text**: - the **language** of the text; - **key phrases, places, people, brands or events** (entities); - how **positive or negative** the text is (**sentiment**); - **syntax**, with tokenization and parts of speech; - it automatically **organizes a collection of text files by topic** (topic modeling); - it detects **PII**, and you can train **custom** classifiers and entity recognisers. **Sample use cases:** - analyse customer interactions (emails) to find what leads to a positive or negative experience; - create and group articles by the topics Comprehend uncovers. ### Amazon Comprehend Medical [#amazon-comprehend-medical] **[Amazon Comprehend Medical](/docs/glossary#term-amazon-comprehend-medical)** detects and returns useful information in **unstructured clinical text**: - physician's notes; - discharge summaries; - test results; - case notes. It uses NLP to **detect Protected Health Information (PHI)** with the **`DetectPHI` API**, and links medical terms to standard codes. Store your documents in **S3**, analyse real-time data with **Data Firehose**, or use **Transcribe** to turn patient narratives into text that Comprehend Medical analyses. ## Real-world examples [#real-world-examples] - **A broadcaster** adds live subtitles to news streams with Transcribe streaming, then translates them into three languages with Translate. - **An e-learning site** narrates every article with Polly, using a lexicon so its product names are pronounced correctly. - **A hotel chain** runs Comprehend over thousands of reviews a day to track sentiment per hotel. ## Exam tips [#exam-tips] - **"Speech to text", "subtitles", "transcribe calls"** → Transcribe. **"Remove PII from transcripts"** → Transcribe redaction. - **"Text to speech"** → Polly. **"Customise pronunciation"** → lexicons. **"Whisper, emphasis, breathing"** → SSML. - **"Translate a website or app"** → Translate. - **"Sentiment analysis", "extract entities or key phrases"** → Comprehend. - **"Medical notes", "detect PHI"** → Comprehend Medical. ## Common traps [#common-traps] - **"Polly converts speech to text."** Polly speaks (text to speech); Transcribe listens (speech to text). - **"Comprehend for clinical PHI."** Use Comprehend Medical for clinical text. ## Hands-on lab: make Polly whisper [#hands-on-lab-make-polly-whisper] **Goal:** generate speech from SSML and hear the difference. Polly costs from $4 per million characters (standard voices) to more for neural, long-form and generative voices, so a few sentences cost **far less than a cent**. Any Region with Polly works. ### Plain text [#plain-text] Open **Polly → Text-to-Speech**. Choose a neural English voice, type `AWS makes this easy`, and click **Listen**. ### SSML [#ssml] Switch on **SSML** and enter: ```xml Amazon Web Services makes this easy. Even at night. ``` Choose a standard voice (whispering is supported on standard voices) and click **Listen**. **Expected result:** the second version stresses "easy" and whispers the last sentence. **Clean up:** nothing to delete. ## AWS documentation [#aws-documentation] - [What is Amazon Transcribe?](https://docs.aws.amazon.com/transcribe/latest/dg/what-is.html) - [Redacting PII in Transcribe](https://docs.aws.amazon.com/transcribe/latest/dg/pii-redaction.html) - [What is Amazon Polly?](https://docs.aws.amazon.com/polly/latest/dg/what-is.html) - [Managing lexicons](https://docs.aws.amazon.com/polly/latest/dg/managing-lexicons.html) - [Generating speech from SSML documents](https://docs.aws.amazon.com/polly/latest/dg/ssml.html) - [What is Amazon Translate?](https://docs.aws.amazon.com/translate/latest/dg/what-is.html) - [What is Amazon Comprehend?](https://docs.aws.amazon.com/comprehend/latest/dg/what-is.html) - [What is Amazon Comprehend Medical?](https://docs.aws.amazon.com/comprehend-medical/latest/dev/comprehendmedical-welcome.html) # Rekognition and Textract (/docs/ml/vision-documents) ## Amazon Rekognition [#amazon-rekognition] **[Amazon Rekognition](/docs/glossary#term-amazon-rekognition)** finds **objects, people, text and scenes** in **images and videos** using machine learning. - **Facial analysis** and **facial search**, for user verification and people counting. - Create a database of **"familiar faces"** (a face collection), or compare against **celebrities**. - Works on images and stored videos in S3, and on **streaming video** (for example from Kinesis Video Streams). - **Custom Labels:** train it to recognise things specific to you, such as your logo or products. **Use cases:** - labelling (tag photos with "beach", "car", "dog"); - **content moderation**; - text detection (text in photos, such as street signs); - face detection and analysis (age range, emotions…); - face search and verification; - celebrity recognition. The slides list **pathing** (tracking people through a video, for example for sports game analysis). AWS **ended support for Rekognition People Pathing on 31 October 2025**, so it's no longer available. ## Rekognition content moderation [#rekognition-content-moderation]
![Rekognition content moderation: a user uploads an image or video; Rekognition returns moderation labels with confidence scores; items whose confidence is at or above your minimum threshold are flagged and can go to Amazon Augmented AI for human review, and the rest are published](/diagrams/ml-rekognition-moderation.light.svg) ![Rekognition content moderation: a user uploads an image or video; Rekognition returns moderation labels with confidence scores; items whose confidence is at or above your minimum threshold are flagged and can go to Amazon Augmented AI for human review, and the rest are published](/diagrams/ml-rekognition-moderation.dark.svg)
Flag above your threshold, let humans review.
- **Detect content that is inappropriate, unwanted or offensive** in images and videos. - Used in social media, broadcast media, advertising and e-commerce to create a **safer user experience**. - **Set a minimum confidence threshold** for the items that will be flagged: a higher threshold flags less, with fewer false alarms. - **Flag sensitive content for manual review** in **[Amazon Augmented AI (A2I)](/docs/glossary#term-amazon-augmented-ai)**, which is built into Rekognition. - Helps **comply with regulations**. ## Amazon Textract [#amazon-textract]
![Amazon Textract: a scanned driving licence is analysed by Textract, which returns structured fields such as document ID, name, date of birth and class; Textract reads printed text, handwriting, forms, tables, and identity documents and invoices](/diagrams/ml-textract.light.svg) ![Amazon Textract: a scanned driving licence is analysed by Textract, which returns structured fields such as document ID, name, date of birth and class; Textract reads printed text, handwriting, forms, tables, and identity documents and invoices](/diagrams/ml-textract.dark.svg)
From a scanned document to structured data.
**[Amazon Textract](/docs/glossary#term-amazon-textract)** **automatically extracts text, handwriting and data** from any scanned document using AI and ML. - **Extract data from forms and tables** (key-value pairs like `Name: Jane Doe`, table cells), not just raw text. - Read and process **any type of document** (PDFs, images…). - Specialised analysis for **invoices and receipts**, **identity documents** (driving licences, passports) and **mortgage loan packages**. - **Queries:** ask for a field in plain language ("What is the policy number?"). **Use cases:** - **financial services:** invoices, financial reports; - **healthcare:** medical records, insurance claims; - **public sector:** tax forms, ID documents, passports. Textract now also has **Textract Insights**, a generative AI capability that turns mixed documents into structured data you define. It's newer than the course. ## Real-world examples [#real-world-examples] - **A photo-sharing app** runs every upload through Rekognition moderation and sends borderline images to human reviewers in A2I. - **A bank** uses Rekognition face comparison to check that a selfie matches the photo on an ID card during account opening. - **An insurer** extracts claim numbers, dates and amounts from thousands of scanned claim forms a day with Textract. ## Exam tips [#exam-tips] - **"Detect objects, scenes, faces, celebrities in images or video"** → Rekognition. - **"Moderate user-generated images and videos"** → Rekognition content moderation (+ A2I for human review). - **"Human review of low-confidence ML results"** → Amazon Augmented AI (A2I). - **"Extract text and data from scanned forms, tables, invoices, IDs"** → Textract. ## Common traps [#common-traps] - **"Textract for faces"** or **"Rekognition for invoice tables."** Images and video → Rekognition; documents → Textract. - **"Lower the confidence threshold to reduce false positives."** A lower threshold flags more; raise it to flag less. ## Hands-on lab: label an image with Rekognition [#hands-on-lab-label-an-image-with-rekognition] **Goal:** see Rekognition labels and moderation results on your own image. Rekognition image analysis costs about **$0.001 per image**, so a few tests cost less than a cent. Use a Region where Rekognition is available, such as us-east-1. ### Detect labels [#detect-labels] Open **Rekognition → Label detection** (under Demos). Upload a photo, for example of your desk. ### Read the results [#read-the-results] Look at the labels ("Laptop", "Cup"…) and the confidence for each. Expand the **Response** to see the JSON the API returns. ### Try moderation [#try-moderation] Open **Content moderation** under Demos with the same photo. A normal photo returns no moderation labels. **Expected result:** a list of labels with confidence scores, and an empty moderation result. **Clean up:** nothing to delete; the demo doesn't store your image. ## AWS documentation [#aws-documentation] - [What is Amazon Rekognition?](https://docs.aws.amazon.com/rekognition/latest/dg/what-is.html) - [Moderating content](https://docs.aws.amazon.com/rekognition/latest/dg/moderation.html) - [Reviewing inappropriate content with Amazon A2I](https://docs.aws.amazon.com/rekognition/latest/dg/a2i-rekognition.html) - [What is Amazon Textract?](https://docs.aws.amazon.com/textract/latest/dg/what-is.html) # Access Points and Object Lambda (/docs/s3/access-points-object-lambda) ## S3 Access Points [#s3-access-points]
![S3 Access Points: the finance, sales and analytics teams each use their own access point, with its own DNS name and policy: read and write under /finance/, read and write under /sales/, or read the whole bucket; the bucket policy stays simple](/diagrams/s3-access-points.light.svg) ![S3 Access Points: the finance, sales and analytics teams each use their own access point, with its own DNS name and policy: read and write under /finance/, read and write under /sales/, or read the whole bucket; the bucket policy stays simple](/diagrams/s3-access-points.dark.svg)
One entry point per team, each with its own policy.
A shared bucket used by many teams ends up with a huge, fragile bucket policy. **[S3 Access Points](/docs/glossary#term-s3-access-point)** **simplify security management** for such buckets. Each access point has: - its **own DNS name**, with a **network origin** of either **internet** or **VPC**; - an **access point policy** (similar to a bucket policy), so you **manage security at scale**, one team or application at a time. In the example: - the **Finance** access point policy grants read/write to the `/finance` prefix; - the **Sales** access point policy grants read/write to the `/sales` prefix; - the **Analytics** access point policy grants read to the whole bucket. The bucket policy stays simple: it **delegates** access control to the access points. ### VPC origin [#vpc-origin] - You can define an access point to be accessible **only from within a VPC**. - You must create a **VPC endpoint** for S3 (Gateway or Interface endpoint) to reach it. See [VPC endpoints](/docs/vpc/vpc-endpoints-privatelink). - The **VPC endpoint policy** must allow access to both the target **bucket** and the **access point**. So a request from an EC2 instance passes three policies: the **endpoint policy**, the **access point policy** and the **bucket policy**. ## S3 Object Lambda [#s3-object-lambda] **S3 Object Lambda** uses **AWS Lambda functions to change an object as it's retrieved** by the calling application. - Only **one S3 bucket** is needed. On top of it you create a supporting **S3 Access Point** and one or more **S3 Object Lambda Access Points**, each linked to a Lambda function. - An application reads through an Object Lambda Access Point; the function fetches the original object, changes it and returns the result. The stored object never changes. - **Use cases:** - **redacting** personally identifiable information for analytics or non-production environments; - **converting** data formats, such as XML to JSON; - **resizing and watermarking** images on the fly, using details of the user who asked. For example, an e-commerce app reads the original object; an analytics app reads a redacted copy; a marketing app reads a copy enriched with data from a customer loyalty database, all from the same bucket. Since **7 November 2025**, S3 Object Lambda is available **only to existing customers** (and some AWS partners). New designs do the same with CloudFront functions, Lambda behind API Gateway, or processing at write time. It can still appear on the exam as "transform objects on retrieval without storing copies". ## Real-world examples [#real-world-examples] - **A data lake shared by 30 teams** gives each team an access point with a policy limited to its prefix, instead of one 20 KB bucket policy. - **A bank** creates a VPC-only access point, so its data can only be reached from inside its private network. - **A healthcare company** uses Object Lambda to strip patient names from records when the analytics team reads them. ## Exam tips [#exam-tips] - **"Many teams share a bucket, the bucket policy is too complex"** → S3 Access Points with per-team policies. - **"Access the bucket only from inside a VPC"** → an access point with VPC network origin, plus a VPC endpoint. - **"Change data as it's read, without storing copies"** (redact, convert, resize) → S3 Object Lambda. ## Common traps [#common-traps] - **"Create a copy of the bucket per team."** Access points give separate entry points to one bucket. - **"A VPC access point works without a VPC endpoint."** It needs one, and the endpoint policy must allow the access point and bucket. - **"Object Lambda changes the stored object."** It changes only what the caller receives. ## Hands-on lab: an access point [#hands-on-lab-an-access-point] **Goal:** create an access point for your bucket and read an object through it. Access points are free; a few requests cost **less than a cent**. Any Region works. ### Create the access point [#create-the-access-point] **S3 → Access Points → Create access point**. Name `saa-ap`, bucket: your lab bucket, network origin **Internet**. Keep Block Public Access on. Create. ### Read through it [#read-through-it] Open `saa-ap` and copy its **access point alias** (it looks like a bucket name ending in `-s3alias`). In CloudShell: ```bash aws s3 ls s3:/// ``` You see the bucket's objects: the access point is another way into the same bucket. (Your own IAM permissions allow it; for other users you'd add an access point policy.) **Expected result:** the same objects listed through the access point's own name. **Clean up:** delete `saa-ap`. When you've finished all the S3 labs, empty and delete your lab bucket (with **Show versions** on, so old versions go too). ## AWS documentation [#aws-documentation] - [Managing access to shared datasets with access points](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-points.html) - [Creating access points restricted to a VPC](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-points-vpc.html) - [Transforming objects with S3 Object Lambda](https://docs.aws.amazon.com/AmazonS3/latest/userguide/transforming-objects.html) # Batch Operations and Storage Lens (/docs/s3/batch-operations-storage-lens) ## S3 Batch Operations [#s3-batch-operations]
![S3 Batch Operations: S3 Inventory lists the objects, Athena filters the list into a manifest, and a Batch Operations job runs one operation on every object in it, retrying failures, tracking progress and writing a completion report](/diagrams/s3-batch-operations.light.svg) ![S3 Batch Operations: S3 Inventory lists the objects, Athena filters the list into a manifest, and a Batch Operations job runs one operation on every object in it, retrying failures, tracking progress and writing a completion report](/diagrams/s3-batch-operations.dark.svg)
One job, millions of objects.
**[S3 Batch Operations](/docs/glossary#term-s3-batch-operations)** performs **bulk operations on existing objects** with a single request. For example: - modify object **metadata and properties**; - **copy** objects between buckets; - **encrypt unencrypted objects** (or change their encryption); - modify **ACLs** and **tags**; - **restore** objects from S3 Glacier; - **invoke a Lambda function** to do a custom action on each object; - **replicate** existing objects (S3 Batch Replication). How it works: 1. A **job** has a **list of objects** (the *manifest*), the **action** to perform and optional **parameters**. 2. The manifest is an **S3 Inventory** report or a CSV file. A common pattern is to get the full list from **S3 Inventory** and filter it with **Athena** (for example, "all unencrypted objects"). 3. S3 Batch Operations runs the job: it **retries** failures, **tracks progress**, sends **completion notifications** and writes a **completion report**. ## S3 Storage Lens [#s3-storage-lens] **[S3 Storage Lens](/docs/glossary#term-s3-storage-lens)** helps you **understand, analyse and optimize** storage across your **whole AWS Organization**. - **Discover anomalies**, find **cost savings**, and check **data protection** best practices, with usage and activity metrics. - **Aggregate** data for the organization, specific accounts, Regions, buckets or prefixes. - A **default dashboard**, or dashboards of your own. - **Export metrics daily** to an S3 bucket in **CSV or Parquet** format. ### The default dashboard [#the-default-dashboard] - Shows summarized insights and trends, for both free and advanced metrics. - Shows **multi-Region** and **multi-account** data. - **Preconfigured** by Amazon S3. It **can't be deleted**, but it can be disabled. ### Metrics [#metrics] - **Summary:** general insights, such as `StorageBytes` and `ObjectCount`. Find the fastest-growing (or unused) buckets and prefixes. - **Cost optimization:** such as `NonCurrentVersionStorageBytes` and `IncompleteMultipartUploadStorageBytes`. Find buckets with incomplete multipart uploads older than 7 days, or objects that could move to a cheaper class. - **Data protection:** such as `VersioningEnabledBucketCount`, `MFADeleteEnabledBucketCount`, `SSEKMSEnabledBucketCount`, `CrossRegionReplicationRuleCount`. Find buckets that don't follow best practices. - **Access management:** Object Ownership settings in use. - **Event:** which buckets have S3 Event Notifications. - **Performance:** which buckets have Transfer Acceleration. - **Activity:** how storage is requested: `AllRequests`, `GetRequests`, `PutRequests`, `BytesDownloaded`. - **Detailed status codes:** `200OKStatusCount`, `403ForbiddenErrorCount`, `404NotFoundErrorCount`. ### Free vs advanced [#free-vs-advanced] - **Free metrics:** available to every customer automatically; about 28 usage metrics; data kept for queries for **14 days**. - **Advanced metrics and recommendations** (paid): - more metrics: activity, advanced cost optimization, advanced data protection, status codes; - **CloudWatch publishing**, so you can use the metrics in CloudWatch at no extra charge; - **prefix aggregation**, metrics at prefix level; - data kept for **15 months**. ## Real-world examples [#real-world-examples] - **A company discovers 40 million unencrypted objects** from before 2023. An S3 Inventory report filtered with Athena feeds a Batch Operations job that re-encrypts them all with SSE-KMS. - **A FinOps team** opens the Storage Lens dashboard and finds 3 TB of incomplete multipart uploads across 50 accounts, then adds lifecycle rules to clean them up. ## Exam tips [#exam-tips] - **"Encrypt all existing unencrypted objects", "change tags on millions of objects"** → S3 Batch Operations (with S3 Inventory as the list). - **"Restore many objects from Glacier at once"** → Batch Operations. - **"Replicate existing objects"** → S3 Batch Replication. - **"Organization-wide view of S3 usage, cost savings and data protection"** → S3 Storage Lens. - **"Keep Storage Lens metrics 15 months", "publish to CloudWatch"** → advanced metrics. ## Common traps [#common-traps] - **"Write a script to loop over millions of objects."** Batch Operations does it with retries and a report. - **"Storage Lens free metrics keep a year of history."** Free data is queryable for 14 days; advanced for 15 months. ## Hands-on lab: the Storage Lens dashboard [#hands-on-lab-the-storage-lens-dashboard] **Goal:** open the default Storage Lens dashboard and read what it says about your account. The default dashboard with free metrics costs **nothing**. Don't upgrade to advanced metrics for this lab. Any Region works. ### Open the default dashboard [#open-the-default-dashboard] **S3 → Storage Lens → Dashboards → default-account-dashboard**. It may show data from the last day only if your account is new: Storage Lens updates daily. ### Explore [#explore] Look at **Total storage**, **Object count** and the trend charts. Open the **Cost optimization** and **Data protection** tabs to see which of your buckets have versioning or encryption turned on. **Expected result:** an account-wide picture of your S3 storage, without any setup. **Clean up:** nothing to delete. ## AWS documentation [#aws-documentation] - [Performing object operations in bulk with Batch Operations](https://docs.aws.amazon.com/AmazonS3/latest/userguide/batch-ops.html) - [Assessing your storage activity and usage with S3 Storage Lens](https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage_lens.html) - [S3 Storage Lens metrics and features](https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage_lens_basics_metrics_recommendations.html) # CORS (/docs/s3/cors) ## What it is [#what-it-is] Web browsers protect users with the **same-origin policy**: JavaScript on a page from one website can't freely read responses from another website. **[CORS](/docs/glossary#term-cors)** (Cross-Origin Resource Sharing) is how the other website says "requests from that origin are allowed". An **origin** is the **scheme (protocol) + host (domain) + port**. In `https://www.example.com`, the port is implied: 443 for HTTPS, 80 for HTTP. - **Same origin:** `http://example.com/app1` and `http://example.com/app2`. - **Different origins:** `http://www.example.com` and `http://other.example.com`. Requests to another origin aren't fulfilled by the browser **unless the other origin allows them**, using **CORS headers** such as `Access-Control-Allow-Origin`. ### How the browser checks [#how-the-browser-checks] 1. The page on `https://www.example.com` wants to call `https://www.other.com`. 2. For anything beyond a simple GET, the browser first sends a **preflight request**: an HTTP `OPTIONS` request with the header `Origin: https://www.example.com`. 3. The other server answers with CORS headers, such as `Access-Control-Allow-Origin: https://www.example.com` and `Access-Control-Allow-Methods: GET, PUT, DELETE`. 4. If the origin and method are allowed, the browser makes the real request. CORS is enforced by **browsers**. Other clients, such as the AWS CLI or a server, ignore it. ## CORS on Amazon S3 [#cors-on-amazon-s3]
![CORS: a browser loads index.html from the www.example.com bucket, then asks the assets.example.com bucket for coffee.jpg with an Origin header; the assets bucket has a CORS rule for www.example.com, so it answers with Access-Control-Allow-Origin and the browser allows the response](/diagrams/s3-cors.light.svg) ![CORS: a browser loads index.html from the www.example.com bucket, then asks the assets.example.com bucket for coffee.jpg with an Origin header; the assets bucket has a CORS rule for www.example.com, so it answers with Access-Control-Allow-Origin and the browser allows the response](/diagrams/s3-cors.dark.svg)
The second bucket must allow the first bucket's origin.
If a client makes a cross-origin request to your bucket, you must turn on the right **CORS headers** on that bucket. **It's a popular exam question.** 1. The browser loads `index.html` from the **website bucket**. 2. The page needs `coffee.jpg` from a second, **assets bucket**. The browser asks for it, sending its `Origin`. 3. The assets bucket has a **CORS configuration** that allows that origin, so it answers with `Access-Control-Allow-Origin`, and the browser accepts the image. You can allow a **specific origin** or `*` (all origins). A CORS configuration on the bucket looks like: ```json [ { "AllowedOrigins": ["http://www.example.com"], "AllowedMethods": ["GET"], "AllowedHeaders": ["*"], "MaxAgeSeconds": 3000 } ] ``` The CORS settings go on the bucket that **receives** the cross-origin request (the assets bucket), not on the bucket that served the page. ## Real-world examples [#real-world-examples] - **A web app** at `app.example.com` uploads files straight from the browser to an S3 bucket. The bucket's CORS rules allow `PUT` from `https://app.example.com`. - **A static site** loads fonts and images from a separate assets bucket; that bucket allows the site's origin. ## Exam tips [#exam-tips] - **"Website on one bucket can't load files from another bucket", "browser blocks the request", "CORS error"** → add a CORS configuration to the bucket being requested, allowing the website's origin. - **"Allow any website to load these public files"** → CORS with `AllowedOrigins: ["*"]`. ## Common traps [#common-traps] - **"Fix CORS with a bucket policy."** Bucket policies control permissions; CORS is a separate bucket setting. - **"Configure CORS on the bucket that serves the HTML."** It goes on the bucket the browser is calling cross-origin. ## Hands-on lab: two buckets and a CORS rule [#hands-on-lab-two-buckets-and-a-cors-rule] **Goal:** see a browser block a cross-origin request, then allow it with CORS. Two small website buckets and a few requests cost **less than a cent**. Any Region works. **Before you start:** set up a website bucket as in the [static website lab](/docs/s3/static-website#hands-on-lab-a-website-in-a-bucket). ### Create the assets bucket [#create-the-assets-bucket] Create a second bucket `saa-assets-`, make it a public static website the same way, and upload `extra.html` containing `

Loaded from the other bucket

`.
### Fetch it from the first site [#fetch-it-from-the-first-site] Replace `index.html` in the first bucket with: ```html

Hello from S3

``` Open the first site and the browser's developer console: a **CORS error**, and the text doesn't appear.
### Add the CORS rule [#add-the-cors-rule] On `saa-assets-`, **Permissions → Cross-origin resource sharing (CORS) → Edit**. Paste the configuration above with `AllowedOrigins` set to your first site's website endpoint (starting `http://`, no trailing slash). Save and reload the first site: the text from the other bucket appears.
**Expected result:** the browser only accepts the cross-origin response once the assets bucket allows the site's origin. **Clean up:** empty and delete both buckets. ## AWS documentation [#aws-documentation] - [Using cross-origin resource sharing (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors.html) # Encryption (/docs/s3/encryption) ## The options [#the-options]
![S3 encryption options: server-side, S3 encrypts with SSE-S3 (a key owned by S3, on by default, header AES256), SSE-KMS (a key in AWS KMS, audited in CloudTrail, header aws:kms), DSSE-KMS (a KMS key plus an S3 key, two layers, header aws:kms:dsse) or SSE-C (your key sent in the headers of every request, HTTPS only); with client-side encryption you encrypt before upload and S3 stores only encrypted bytes](/diagrams/s3-encryption-options.light.svg) ![S3 encryption options: server-side, S3 encrypts with SSE-S3 (a key owned by S3, on by default, header AES256), SSE-KMS (a key in AWS KMS, audited in CloudTrail, header aws:kms), DSSE-KMS (a KMS key plus an S3 key, two layers, header aws:kms:dsse) or SSE-C (your key sent in the headers of every request, HTTPS only); with client-side encryption you encrypt before upload and S3 stores only encrypted bytes](/diagrams/s3-encryption-options.dark.svg)
Who holds the key, and who does the encrypting.
You can encrypt objects in S3 in these ways. Knowing which one fits which situation is a common exam question. - **Server-side encryption (SSE):** S3 encrypts objects when it stores them and decrypts them when you read them. - **SSE-S3:** keys managed by Amazon S3. **On by default.** - **SSE-KMS:** keys in **AWS KMS**. - **DSSE-KMS:** two layers of encryption, one with a KMS key. - **SSE-C:** keys you provide with each request. - **Client-side encryption:** you encrypt before uploading. ## SSE-S3 [#sse-s3] - Uses keys **handled, managed and owned by AWS**. You never see or manage them. - The object is encrypted **server-side** with **AES-256**. - Request header: `"x-amz-server-side-encryption": "AES256"`. - **On by default** for new buckets and new objects: since January 2023, every new upload is encrypted with at least SSE-S3, at no cost. ## SSE-KMS [#sse-kms] - Uses keys managed in **[AWS KMS](/docs/glossary#term-aws-kms)** (Key Management Service): the AWS managed key `aws/s3` or a customer managed key. - **Advantages:** you **control** the key (key policy, rotation, disabling it) and every use of the key is **audited** in **CloudTrail**. - Request header: `"x-amz-server-side-encryption": "aws:kms"`. - To read an object, a user needs permission on **both** the object and the **KMS key**. ### The KMS limitation [#the-kms-limitation]
![SSE-KMS: for every upload S3 calls AWS KMS GenerateDataKey, and for every download it calls Decrypt; each call counts against the KMS request quota, and S3 Bucket Keys cut these calls by up to 99 percent](/diagrams/s3-sse-kms.light.svg) ![SSE-KMS: for every upload S3 calls AWS KMS GenerateDataKey, and for every download it calls Decrypt; each call counts against the KMS request quota, and S3 Bucket Keys cut these calls by up to 99 percent](/diagrams/s3-sse-kms.dark.svg)
Every upload and download is a call to KMS.
- Each **upload** makes S3 call the KMS **`GenerateDataKey`** API, and each **download** calls **`Decrypt`**. - These calls count towards the **KMS requests-per-second quota**: 10,000, 20,000 or 100,000 per second depending on the Region. A very busy bucket can be **throttled** by KMS. - You can ask for a higher quota in the **Service Quotas** console. - **S3 Bucket Keys** let S3 use a short-lived bucket-level key, cutting calls to KMS (and their cost) by **up to 99%**. The slides give KMS quotas of 5,500, 10,000 or 30,000 requests per second. The AWS documentation now lists **10,000, 20,000 or 100,000** depending on the Region. The exam point is unchanged: SSE-KMS at very high request rates can hit the KMS quota. ## DSSE-KMS [#dsse-kms] - **Dual-layer server-side encryption:** each object is encrypted **twice**: first with a data key from your **KMS key**, then again with a separate key managed by S3. - For **compliance standards** that require **multi-layer** encryption. It costs more and adds a little latency compared with SSE-KMS. - Request header: `"x-amz-server-side-encryption": "aws:kms:dsse"`. ## SSE-C [#sse-c] - Server-side encryption using keys **fully managed by you, outside AWS**. - You send the key in the **HTTP headers of every request**; S3 uses it to encrypt or decrypt, then **discards it**. S3 **doesn't store** your key. - **HTTPS must be used.** - If you lose the key, you lose the data. Since **April 2026**, SSE-C is **disabled by default** for new buckets (and existing buckets in accounts with no SSE-C objects). To use it, you must explicitly allow it in the bucket's default encryption settings. ## Client-side encryption [#client-side-encryption] - You encrypt data **yourself** before sending it to S3, using a library such as the **Amazon S3 Encryption Client**. - You decrypt it yourself after downloading. - You **fully manage** the keys and the encryption cycle. S3 only ever stores encrypted bytes. ## Encryption in transit [#encryption-in-transit] - Encryption in flight uses **TLS** (often still called SSL). - S3 has an **HTTP** endpoint (not encrypted) and an **HTTPS** endpoint (encrypted in flight). - **HTTPS is recommended**, and most clients use it by default. **HTTPS is mandatory for SSE-C.** ### Forcing encryption in transit [#forcing-encryption-in-transit] A bucket policy can refuse any request that doesn't use HTTPS, with the `aws:SecureTransport` condition: ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Deny", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "Condition": { "Bool": { "aws:SecureTransport": "false" } } } ] } ``` Requests over plain HTTP are denied; HTTPS requests go through. ## Default encryption vs bucket policies [#default-encryption-vs-bucket-policies] - **Default encryption** (SSE-S3 unless you choose SSE-KMS or DSSE-KMS) is applied automatically to new objects that don't ask for anything else. - To **force** a particular kind, use a **bucket policy** that denies `s3:PutObject` without the right header, for example `"StringNotEquals": {"s3:x-amz-server-side-encryption": "aws:kms"}`, or without SSE-C headers. - **Bucket policies are evaluated before default encryption.** A denied upload never reaches the default encryption step. ## Real-world examples [#real-world-examples] - **A startup** relies on default SSE-S3: every object is encrypted with no work or cost. - **A bank** must control and audit its keys. It uses SSE-KMS with a customer managed key and turns on S3 Bucket Keys to keep KMS costs down. - **A defence contractor** must meet a rule requiring two layers of encryption. It uses DSSE-KMS. - **A company with its own key management system** keeps keys outside AWS: SSE-C, or client-side encryption. ## Exam tips [#exam-tips] - **"Encryption with no management at all"** → SSE-S3 (already on by default). - **"Control the key", "audit key usage", "rotate keys"** → SSE-KMS. - **"KMS throttling errors on a busy bucket"** → S3 Bucket Keys, or ask for a higher KMS quota. - **"Two layers of encryption for compliance"** → DSSE-KMS. - **"Keys must stay outside AWS, S3 does the encryption"** → SSE-C (HTTPS only). - **"Data must be encrypted before it leaves our servers"** → client-side encryption. - **"Refuse uploads over HTTP"** → bucket policy denying when `aws:SecureTransport` is false. - **"Only allow objects encrypted with SSE-KMS"** → bucket policy denying `PutObject` without the `aws:kms` header. ## Common traps [#common-traps] - **"S3 objects aren't encrypted unless you turn it on."** SSE-S3 is on by default. - **"S3 stores the SSE-C key for later."** It never stores it; you send it every time. - **"SSE-KMS has no effect on performance."** KMS calls count against a quota and can throttle. - **"Default encryption overrides a bucket policy."** The policy is evaluated first. ## Hands-on lab: SSE-KMS and forcing HTTPS [#hands-on-lab-sse-kms-and-forcing-https] **Goal:** upload an object with SSE-KMS, and deny plain-HTTP requests with a bucket policy. Using the AWS managed key `aws/s3` has no monthly key charge; a few KMS requests cost **less than a cent**. Any Region works. ### Upload with SSE-KMS [#upload-with-sse-kms] In your lab bucket, **Upload** a file. Under **Properties → Server-side encryption**, choose **Specify an encryption key → SSE-KMS → AWS managed key (aws/s3)**. Upload, then open the object: encryption shows **SSE-KMS** and the key ARN. ### Change the default encryption [#change-the-default-encryption] **Properties → Default encryption → Edit**: choose **SSE-KMS** with `aws/s3` and **Bucket Key: Enable**. New uploads are now encrypted with KMS automatically. ### Deny HTTP [#deny-http] Add the `aws:SecureTransport` bucket policy above, with your bucket name. In CloudShell: ```bash aws s3 cp s3:/// . --endpoint-url http://s3.us-east-1.amazonaws.com aws s3 cp s3:/// . ``` The first command (HTTP) fails with **Access Denied**; the second (HTTPS, the default) works. **Expected result:** objects encrypted with KMS by default, and plain-HTTP requests refused. **Clean up:** delete the bucket policy, set default encryption back to SSE-S3, and delete the test object. ## AWS documentation [#aws-documentation] - [Protecting data with server-side encryption](https://docs.aws.amazon.com/AmazonS3/latest/userguide/serv-side-encryption.html) - [Using server-side encryption with AWS KMS keys (SSE-KMS)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html) - [Using dual-layer server-side encryption (DSSE-KMS)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingDSSEncryption.html) - [Using server-side encryption with customer-provided keys (SSE-C)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ServerSideEncryptionCustomerKeys.html) - [Reducing the cost of SSE-KMS with S3 Bucket Keys](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-key.html) - [AWS KMS request quotas](https://docs.aws.amazon.com/kms/latest/developerguide/requests-per-second.html) # Event notifications (/docs/s3/event-notifications) ## What it is [#what-it-is] Things happen to objects in a bucket: they're created, deleted, restored from Glacier, replicated. **[S3 event notifications](/docs/glossary#term-s3-event-notification)** let other services **react** to those events automatically, instead of checking the bucket over and over. The classic use case: **generate a thumbnail** every time an image is uploaded. ## How it works [#how-it-works]
![S3 event notifications: when a matching event happens, such as a new .jpg object, the bucket sends it to Amazon SNS, Amazon SQS or AWS Lambda; it can also send every event to Amazon EventBridge, whose rules route it to many targets](/diagrams/s3-event-notifications.light.svg) ![S3 event notifications: when a matching event happens, such as a new .jpg object, the bucket sends it to Amazon SNS, Amazon SQS or AWS Lambda; it can also send every event to Amazon EventBridge, whose rules route it to many targets](/diagrams/s3-event-notifications.dark.svg)
The bucket tells other services when something happens.
1. You add an **event notification** to the bucket, choosing: - the **event types**, such as `s3:ObjectCreated:*`, `s3:ObjectRemoved:*`, `s3:ObjectRestore:*` or `s3:Replication:*`; - an optional **filter** on the object name, such as prefix `uploads/` and suffix `.jpg`; - a **destination**: an **SNS topic**, an **SQS queue** or a **Lambda function**. 2. When a matching event happens, S3 sends a JSON message describing it (bucket, key, size, event time) to the destination. 3. You can create **as many** event notifications as you need. Notifications are typically delivered **in seconds**, but can sometimes take **a minute or longer**. SQS **FIFO** queues aren't supported as a direct destination (use EventBridge for that). [SNS](/docs/integration/sns) and [SQS](/docs/integration/sqs) are covered in the [Application Integration](/docs/integration) group, [Lambda](/docs/serverless/lambda) in the [Serverless](/docs/serverless) group. ### Permissions: resource policies, not IAM roles [#permissions-resource-policies-not-iam-roles] S3 doesn't use an IAM role to deliver notifications. Instead, each destination needs a **resource (access) policy** that allows the S3 service to use it: - **SNS topic:** an access policy allowing `s3.amazonaws.com` to `SNS:Publish`; - **SQS queue:** an access policy allowing `s3.amazonaws.com` to `SQS:SendMessage`; - **Lambda function:** a resource-based policy allowing `s3.amazonaws.com` to `lambda:InvokeFunction`. Each usually has a condition that the source is your bucket (`aws:SourceArn`). The console adds the Lambda permission for you. ## S3 events with Amazon EventBridge [#s3-events-with-amazon-eventbridge] You can also turn on **Amazon EventBridge** for the bucket. Then: - **All events** go to EventBridge; you don't pick event types on the bucket. - **Advanced filtering** with JSON rules: on metadata, object size, name and more. - **Many destinations:** EventBridge rules can send events to dozens of AWS services, such as Step Functions, Kinesis Data Streams and Firehose. - **EventBridge features:** archive and replay events, and reliable delivery. See [Amazon EventBridge](/docs/integration/eventbridge). ## Real-world examples [#real-world-examples] - **A photo app** triggers a Lambda function on every new `.jpg` in `uploads/`, which writes a thumbnail to `thumbnails/`. - **A media company** sends new-video events to an SQS queue, and a fleet of EC2 workers transcodes them at its own pace. - **A compliance team** sends every object deletion to EventBridge, which notifies security and records the event. ## Exam tips [#exam-tips] - **"Run code when an object is uploaded", "thumbnail on upload"** → S3 event notification to Lambda. - **"Queue uploaded files for processing"** → event notification to SQS. - **"Notify several subscribers of a new object"** → SNS (fan-out). - **"Advanced filtering, many targets, archive and replay of S3 events"** → EventBridge. - **"S3 can't send to the queue"** → the queue's access policy must allow `s3.amazonaws.com`. ## Common traps [#common-traps] - **"Give S3 an IAM role to send notifications."** Destinations need resource policies instead. - **"Event notifications are instant and exactly once."** Usually seconds, sometimes a minute or more. - **"Send S3 events straight to an SQS FIFO queue."** Not supported directly; use EventBridge. - **"A Lambda function triggered by uploads writes back to the same prefix."** That triggers itself in a loop; write to a different prefix or bucket. ## Hands-on lab: events into an SQS queue [#hands-on-lab-events-into-an-sqs-queue] **Goal:** send upload events from a bucket to an SQS queue and read one. A handful of SQS messages and S3 requests cost **less than a cent**. Any Region works. ### Create a queue that S3 can write to [#create-a-queue-that-s3-can-write-to] **SQS → Create queue**, Standard, name `saa-s3-events`. Under **Access policy → Advanced**, add a statement allowing `"Service": "s3.amazonaws.com"` to `"SQS:SendMessage"` on the queue ARN, with condition `"ArnLike": {"aws:SourceArn": "arn:aws:s3:::"}`. Create. ### Add the notification [#add-the-notification] In your lab bucket, **Properties → Event notifications → Create event notification**. Name `uploads`, prefix `uploads/`, event type **All object create events**, destination **SQS queue** `saa-s3-events`. Save. (If S3 reports it can't validate the destination, the access policy is wrong.) ### Upload and read the message [#upload-and-read-the-message] Upload a file into `uploads/`. In SQS, open the queue → **Send and receive messages → Poll for messages**. Open the newest message: a JSON event with `eventName: ObjectCreated:Put` and your object's key. (The first message may be a `s3:TestEvent`.) **Expected result:** every upload under `uploads/` produces a message in the queue. **Clean up:** delete the event notification, the `saa-s3-events` queue and the test object. ## AWS documentation [#aws-documentation] - [Amazon S3 Event Notifications](https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventNotifications.html) - [Using EventBridge with Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventBridge.html) # Amazon S3 (/docs/s3) ## What it is [#what-it-is] **[Amazon S3](/docs/glossary#term-amazon-s3)** (Simple Storage Service) is AWS's **object storage**. You put files ("objects") into containers ("buckets") and read them back over HTTPS, from anywhere, at any scale. AWS advertises it as storage that scales without limit: you never size a disk or run out of space. S3 is one of the main building blocks of AWS. Many websites are built on it, and many AWS services use it to store logs, backups, exports and data. Object storage is different from the [block and file storage](/docs/storage) of the previous group: you read and write whole objects through an API, rather than attaching a disk to a server. ### What people use it for [#what-people-use-it-for] - **Backup and storage**, **disaster recovery** and **archive**. For example, Nasdaq keeps seven years of data in S3 Glacier. - **Hybrid cloud storage**: extending on-premises storage into AWS. - **Application and media hosting**: images, video and downloads for apps and websites. - **Data lakes and big data analytics**. For example, Sysco runs analytics on its data in S3. - **Software delivery** and **static websites**. ## Buckets [#buckets] A **[bucket](/docs/glossary#term-s3-bucket)** is a container for objects, a bit like a top-level folder. - Buckets are created **in a Region**. S3 looks global in the console, but every bucket and its data live in the Region you choose. - **Names:** a general purpose bucket name has to be unique across **all accounts and all Regions** (a shared global namespace). You can now also create buckets in your **account regional namespace**: the name ends in `-an` and only your account can ever own it, which AWS recommends. - **Naming rules:** - 3 to 63 characters: lowercase letters, numbers, hyphens (and dots); - no uppercase letters and no underscores; - must start and end with a letter or number; - must not look like an IP address; - must not start with `xn--` or end with `-s3alias` or `--ol-s3`. ## Objects and keys [#objects-and-keys]
![An S3 object key is the full path after the bucket name: the prefix photos/2026/ plus the object name beach.jpg; each object also has its value (up to 50 TB), metadata, up to 10 tags and, with versioning, a version ID](/diagrams/s3-object-key.light.svg) ![An S3 object key is the full path after the bucket name: the prefix photos/2026/ plus the object name beach.jpg; each object also has its value (up to 50 TB), metadata, up to 10 tags and, with versioning, a version ID](/diagrams/s3-object-key.dark.svg)
A key is a prefix plus an object name.
- Every object has a **key**: its **full path** inside the bucket, such as `photos/2026/beach.jpg` in `s3://my-bucket/photos/2026/beach.jpg`. - The key is a **[prefix](/docs/glossary#term-s3-prefix)** (`photos/2026/`) plus an **object name** (`beach.jpg`). - **There are no real directories.** Keys are just long names that contain slashes. The console shows "folders" to make browsing easier, but S3 itself only has keys. Each object has: - **A value:** the content, from 0 bytes up to **50 TB**. A single upload (`PUT`) can be at most **5 GB**; anything bigger must use **[multipart upload](/docs/s3/performance#multipart-upload)**. - **Metadata:** key-value pairs, set by the system (content type, size) or by you. - **Tags:** up to **10** key-value pairs, useful for permissions and lifecycle rules. - **A version ID**, if [versioning](/docs/s3/versioning-replication) is on. For years the maximum object size was 5 TB. AWS raised it to **50 TB**, which the slides already show. The **account regional namespace** for bucket names is also new: if a question asks how to make sure no one else can take your bucket names, that's the answer. ## In this group [#in-this-group] ### Basics [#basics] ### Storage classes and cost [#storage-classes-and-cost] ### Advanced [#advanced] ### Security [#security] ## Exam tips [#exam-tips] - **"Store any amount of files cheaply, accessed over HTTP"**, **"durable object storage"** → S3. - **"Object larger than 5 GB"** → multipart upload (required). **Largest object** → 50 TB. - **"Bucket names must be unique"** → globally, unless you use the account regional namespace. - **"S3 is global"** in a question is a trap: buckets are Regional. ## Common traps [#common-traps] - **"Create folders in S3."** Folders are just key prefixes. - **"Mount S3 as a disk on EC2 for a database."** S3 is object storage; databases need block storage (EBS). - **"Bucket names can use uppercase or underscores."** They can't. ## Hands-on lab: your first bucket [#hands-on-lab-your-first-bucket] **Goal:** create a bucket, upload a file into a "folder", and see that the folder is just part of the key. Storing a few small files in S3 Standard costs **less than a cent** a month. Any Region works. ### Create a bucket [#create-a-bucket] **S3 → Create bucket**. Bucket type **General purpose**, name `saa-lab--` (it must be unique), Region us-east-1. Keep **Block all public access** on and the other defaults. Add the tag `Project=saa-lab`. Create. ### Upload into a folder [#upload-into-a-folder] Open the bucket → **Create folder** `photos`. Open it → **Upload** any small image. Open the object: look at its **Key** (`photos/your-image.jpg`), **S3 URI**, size, storage class and **Server-side encryption** (already on). ### See that folders are only prefixes [#see-that-folders-are-only-prefixes] In CloudShell, run: ```bash aws s3api list-objects-v2 --bucket --query 'Contents[].Key' ``` You get `photos/` (the empty "folder" marker the console created) and `photos/your-image.jpg`: just keys. **Expected result:** a private bucket with one object whose key includes its "folder". **Clean up:** keep the bucket for the next labs, or **Empty** it and then **Delete** it. ## AWS documentation [#aws-documentation] - [What is Amazon S3?](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) - [General purpose bucket naming rules](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html) - [Amazon S3 objects overview](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingObjects.html) - [Uploading objects](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html) - [Categorizing your objects using tags](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-tagging.html) # Lifecycle rules (/docs/s3/lifecycle-rules) ## Moving between storage classes [#moving-between-storage-classes] Objects can move from one storage class to a cheaper one as they age. Transitions go **downwards**, from hotter to colder classes: from Standard to any other class, from Standard-IA to Intelligent-Tiering, One Zone-IA or the Glacier classes, and so on down to Glacier Deep Archive. - For objects read less often, move them to **Standard-IA**. - For archives you don't need quickly, move them to **Glacier Flexible Retrieval** or **Glacier Deep Archive**. You could change classes by hand, but **[lifecycle rules](/docs/glossary#term-s3-lifecycle-rule)** do it automatically. ## Lifecycle rules [#lifecycle-rules]
![A lifecycle rule over time: objects start in S3 Standard, transition to Standard-IA after 30 days, to Glacier Flexible Retrieval after 180 days, and expire (are deleted) after 365 days](/diagrams/s3-lifecycle.light.svg) ![A lifecycle rule over time: objects start in S3 Standard, transition to Standard-IA after 30 days, to Glacier Flexible Retrieval after 180 days, and expire (are deleted) after 365 days](/diagrams/s3-lifecycle.dark.svg)
One rule that moves objects down, then deletes them.
A lifecycle rule has two kinds of action: - **Transition actions** move objects to another storage class after a number of days. For example: to Standard-IA **60 days** after creation, then to Glacier Flexible Retrieval after **6 months**. - **Expiration actions** delete objects after some time. For example: - delete **access log files** after 365 days; - delete **old (noncurrent) versions** of objects, if versioning is on; - delete **incomplete multipart uploads**, whose parts you pay for but can't use. A rule can apply to the whole bucket, to a **prefix** (such as `s3://mybucket/mp3/*`), to objects with certain **tags** (such as `Department: Finance`), or to objects in a size range. Things to know: - Objects **smaller than 128 KB** don't transition by default, because each transition is a billed request. - Moving objects into a class with a **minimum duration** (IA, Glacier) before that minimum is up is charged as if they stayed. ## Scenario 1: thumbnails and source images [#scenario-1-thumbnails-and-source-images] *An application on EC2 makes thumbnails of profile photos uploaded to S3. Thumbnails can be re-created easily and only need to be kept for 60 days. The source images must be available immediately for 60 days; after that, users can wait up to 6 hours.* - **Source images:** S3 Standard, with a lifecycle rule to **transition to Glacier Flexible Retrieval after 60 days** (Standard retrieval takes 3 to 5 hours). - **Thumbnails:** **S3 One Zone-IA** (cheap, and they can be re-created), with a rule to **expire them after 60 days**. Use a prefix or tag so each rule only hits its own objects. ## Scenario 2: recovering deleted objects [#scenario-2-recovering-deleted-objects] *Deleted S3 objects must be recoverable immediately for 30 days, although this rarely happens. After that, and for up to 365 days, deleted objects must be recoverable within 48 hours.* - Turn on **S3 Versioning**, so a "deleted" object is only hidden behind a delete marker and its versions remain. - Transition **noncurrent versions** to **Standard-IA** (immediate access, cheaper). - Then transition **noncurrent versions** to **Glacier Deep Archive** (retrieval within 48 hours with Bulk), and expire them after 365 days. ## Storage Class Analysis [#storage-class-analysis] **Storage Class Analysis** (part of S3 Analytics) helps you decide **when** to transition objects. - It watches how objects are accessed and recommends when to move them from **Standard to Standard-IA**. It doesn't cover One Zone-IA or Glacier. - The report is **updated daily**, and you start seeing data **24 to 48 hours** after you turn it on. You can export it as a CSV file to a bucket. - A good first step for writing (or improving) lifecycle rules. ## Real-world examples [#real-world-examples] - **A media company** keeps new videos in Standard, moves them to Standard-IA after 30 days and to Glacier Deep Archive after a year. - **A team forgets about failed uploads** of huge files. A rule that aborts incomplete multipart uploads after 7 days removes gigabytes of hidden, billed parts. - **A versioned bucket's bill keeps growing.** A rule that expires noncurrent versions after 90 days stops it. ## Exam tips [#exam-tips] - **"Automatically move objects to a cheaper class after N days"** → lifecycle transition action. - **"Delete old log files automatically"** → lifecycle expiration action. - **"Old versions are costing money"** → expire noncurrent versions. - **"Hidden storage cost from failed uploads"** → abort incomplete multipart uploads. - **"Which objects should move to Standard-IA, and when?"** → Storage Class Analysis. - **"Recover deleted objects within 48 hours for a year"** → versioning + transition noncurrent versions to Deep Archive. ## Common traps [#common-traps] - **"Lifecycle rules move objects from Glacier back to Standard."** Transitions only go to colder classes; to bring data back, restore and copy it. - **"Storage Class Analysis recommends Glacier transitions."** Only Standard to Standard-IA. - **"Expiration actions are free in any class."** Expiring before a class's minimum duration still incurs the minimum charge. ## Hands-on lab: a lifecycle rule [#hands-on-lab-a-lifecycle-rule] **Goal:** create a rule that tiers and expires objects under a prefix, and cleans up old versions and failed uploads. Creating a rule is free. With only a few test objects, any transitions cost **less than a cent**. Any Region works. ### Create the rule [#create-the-rule] In your versioned lab bucket, **Management → Create lifecycle rule**. Name `logs-tiering`, scope **Limit the scope with filters**, prefix `logs/`. ### Choose the actions [#choose-the-actions] Tick **Transition current versions** (Standard-IA after 30 days, Glacier Flexible Retrieval after 180 days), **Expire current versions** after 365 days, **Permanently delete noncurrent versions** after 30 days, and **Delete incomplete multipart uploads** after 7 days. Acknowledge the warning about small objects, then create. ### Read the timeline [#read-the-timeline] The rule page shows a **Review transition and expiration actions** timeline: day 0, day 30, day 180, day 365. Upload a test file under `logs/`; S3 applies the rule in the background (usually once a day). **Expected result:** a rule that will move `logs/` objects to cheaper classes and delete them after a year, without any code. **Clean up:** delete the rule and the test object. ## AWS documentation [#aws-documentation] - [Managing the lifecycle of objects](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html) - [Transitioning objects using S3 Lifecycle](https://docs.aws.amazon.com/AmazonS3/latest/userguide/lifecycle-transition-general-considerations.html) - [Amazon S3 analytics: Storage Class Analysis](https://docs.aws.amazon.com/AmazonS3/latest/userguide/analytics-storage-class.html) # MFA Delete and access logs (/docs/s3/mfa-delete-access-logs) ## MFA Delete [#mfa-delete] **[MFA Delete](/docs/glossary#term-mfa-delete)** forces users to enter a code from an **MFA device** (an authenticator app or a hardware key) before doing important, destructive operations on S3. MFA is **required** to: - **permanently delete an object version**; - **suspend versioning** on the bucket. MFA is **not required** to: - **enable versioning**; - **list deleted versions**. Rules: - **Versioning must be enabled** on the bucket. - **Only the bucket owner (the root user)** can enable or disable MFA Delete. - It's turned on with the **AWS CLI** (or API), using the root user's credentials and MFA device, not from the console: ```bash aws s3api put-bucket-versioning --bucket my-bucket \ --versioning-configuration Status=Enabled,MFADelete=Enabled \ --mfa "arn:aws:iam::123456789012:mfa/root-account-mfa-device 123456" ``` Because it needs root credentials (and root access keys are a bad idea), it's rarely used in practice; Object Lock is often a better fit. It's still a favourite on the exam. ## S3 server access logs [#s3-server-access-logs]
![Server access logging: every request to the app bucket, allowed or denied, from any account, is recorded as a log record in a separate log bucket in the same Region and account; logging a bucket into itself causes an endless loop](/diagrams/s3-access-logs.light.svg) ![Server access logging: every request to the app bucket, allowed or denied, from any account, is recorded as a log record in a separate log bucket in the same Region and account; logging a bucket into itself causes an endless loop](/diagrams/s3-access-logs.dark.svg)
Every request is written to another bucket.
For audits, you may want a record of **every access** to a bucket. **[Server access logging](/docs/glossary#term-s3-server-access-logs)** does that. - **Any request** made to S3, from **any account**, **allowed or denied**, is logged into **another S3 bucket**. - The logs can be analysed with data analysis tools, such as **[Athena](/docs/analytics/athena)**. - The **log bucket must be in the same Region** (and, per the AWS documentation, the **same account**) as the source bucket. - Logs are delivered on a **best-effort** basis, usually within a few hours. - The log format is documented on the [server access log format page](https://docs.aws.amazon.com/AmazonS3/latest/userguide/LogFormat.html). For API-level auditing with guaranteed delivery, use **[AWS CloudTrail](/docs/management/cloudtrail)** (data events); server access logs add request details such as the HTTP status and bytes sent. ### Warning: the logging loop [#warning-the-logging-loop] **Never set the logging bucket to be the bucket you're monitoring.** Every log record written into the bucket is itself a request, which creates another log record, and so on: a **logging loop**. The bucket grows **exponentially**, and so does your bill. ## Real-world examples [#real-world-examples] - **A legal team** must prove that no one has permanently deleted records. MFA Delete on the versioned bucket means a deletion needs the root user's MFA device. - **A security team** turns on server access logging for a sensitive bucket and queries the logs with Athena to find every `403` error from unknown IP addresses. ## Exam tips [#exam-tips] - **"Require MFA to permanently delete object versions"** → MFA Delete (versioning required, root user, CLI). - **"Who can enable MFA Delete?"** → only the bucket owner's root user. - **"Audit all requests to a bucket, including denied ones"** → S3 server access logging to another bucket. - **"Log bucket grows uncontrollably"** → it's logging into itself. ## Common traps [#common-traps] - **"An IAM admin can enable MFA Delete."** Only the root user can. - **"MFA Delete is needed to enable versioning."** Only to suspend versioning or permanently delete versions. - **"Send access logs to the same bucket to keep things simple."** That creates a logging loop. - **"Log bucket in another Region."** It must be in the same Region. ## Hands-on lab: turn on server access logging [#hands-on-lab-turn-on-server-access-logging] **Goal:** log requests to your lab bucket into a separate log bucket. Log files for a few requests cost **less than a cent**. Any Region works. (MFA Delete isn't part of this lab: it needs root access keys, which you shouldn't create.) ### Create the log bucket [#create-the-log-bucket] Create a bucket `saa-logs-` in the **same Region** as your lab bucket, with tag `Project=saa-lab`. ### Turn on logging [#turn-on-logging] On your lab bucket, **Properties → Server access logging → Edit → Enable**. Destination `s3://saa-logs-/lab/`. Save; S3 updates the log bucket's policy so the logging service can write to it. ### Make requests and wait [#make-requests-and-wait] List and download a few objects in the lab bucket, and try to open one through its public URL (denied). After an hour or more, `saa-logs-/lab/` contains log files. Open one: each line is a request, with the operation, key, HTTP status and requester. **Expected result:** a separate bucket collecting a log line for every request to your lab bucket, allowed or denied. **Clean up:** turn off server access logging on the lab bucket, then empty and delete `saa-logs-`. ## AWS documentation [#aws-documentation] - [Configuring MFA delete](https://docs.aws.amazon.com/AmazonS3/latest/userguide/MultiFactorAuthenticationDelete.html) - [Logging requests with server access logging](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ServerLogs.html) - [Enabling Amazon S3 server access logging](https://docs.aws.amazon.com/AmazonS3/latest/userguide/enable-server-access-logging.html) # Object Lock and Vault Lock (/docs/s3/object-lock-vault-lock) ## What it is [#what-it-is] Some data must never be changed or deleted for a period: financial records, medical images, audit logs. Regulations (such as SEC 17a-4 in the US) call this **WORM** storage: **Write Once, Read Many**. S3 offers two ways to get it. ## S3 Glacier Vault Lock [#s3-glacier-vault-lock] **Vault Lock** applies to **vaults** in the original Amazon S3 Glacier service (a vault is Glacier's own container, separate from S3 buckets). 1. You create a **Vault Lock policy** with WORM rules, such as "deny deleting archives younger than 365 days". 2. You **lock** the policy. You have 24 hours to test it before confirming. 3. Once locked, the policy **can never be changed or deleted**, not even by the root user. It's helpful for **compliance and data retention**. The original vault-based Amazon Glacier service is **no longer accepting new customers**. New designs use the **S3 Glacier storage classes** in normal S3 buckets, protected with **S3 Object Lock**. Vault Lock can still appear on the exam as "the WORM option for Glacier vaults". ## S3 Object Lock [#s3-object-lock]
![S3 Object Lock: in governance mode only users with the s3:BypassGovernanceRetention permission can delete a locked version; in compliance mode no one can, not even the root user, until the retain-until date; a legal hold blocks deletion until someone with s3:PutObjectLegalHold removes it](/diagrams/s3-object-lock.light.svg) ![S3 Object Lock: in governance mode only users with the s3:BypassGovernanceRetention permission can delete a locked version; in compliance mode no one can, not even the root user, until the retain-until date; a legal hold blocks deletion until someone with s3:PutObjectLegalHold removes it](/diagrams/s3-object-lock.dark.svg)
Three ways to stop a version being deleted.
**[S3 Object Lock](/docs/glossary#term-s3-object-lock)** adopts the WORM model for objects in S3 buckets. It **blocks an object version from being deleted or overwritten** for a set amount of time. **Versioning must be enabled.** Locks apply to **versions**: uploading the same key just adds a new version, and the locked one stays. ### Retention modes [#retention-modes] - **Compliance mode:** - the object version **can't be overwritten or deleted by any user, including the root user**; - the retention mode **can't be changed**, and the retention period **can't be shortened**. - **Governance mode:** - **most users** can't overwrite or delete the version or change its lock settings; - **some users** with special permission (`s3:BypassGovernanceRetention`) can change the retention or delete the object. ### Retention period and legal hold [#retention-period-and-legal-hold] - **Retention period:** protects the object version for a **fixed period** (until a retain-until date). It **can be extended**, never shortened in compliance mode. - **Legal hold:** - protects the object version **indefinitely**, independent of any retention period; - can be freely **placed and removed** by users with the **`s3:PutObjectLegalHold`** IAM permission. You can also set a **default retention** on the bucket, applied to every new object. ## Real-world examples [#real-world-examples] - **A broker-dealer** stores trade records in a bucket with Object Lock in **compliance mode** for 7 years. Not even AWS support or the root user can delete them early. - **A company** uses **governance mode** for backups: protected from accidental deletion and ransomware, but a security admin can still remove a mistaken upload. - **A lawsuit** requires keeping certain emails. The legal team puts **legal holds** on them until the case ends, then removes the holds. ## Exam tips [#exam-tips] - **"WORM", "regulatory retention", "no one can delete, not even root"** → S3 Object Lock in compliance mode. - **"Prevent deletion but let a few admins override"** → governance mode. - **"Keep an object indefinitely for a lawsuit, no fixed date"** → legal hold. - **"WORM for a Glacier vault"** → Glacier Vault Lock. - **"Object Lock prerequisite"** → versioning enabled. ## Common traps [#common-traps] - **"The root user can delete an object in compliance mode."** No one can, until the retention ends. - **"Shorten a compliance-mode retention period."** Only extending is allowed. - **"A legal hold expires after the retention period."** It has no expiry; someone must remove it. ## Check yourself [#check-yourself] A compliance-mode lab would leave objects you can't delete (and must keep paying for) until the retention ends, so instead: S3 Object Lock in compliance mode with a 5-year retention period (versioning on). Not even the root user can delete or shorten it. Object Lock in governance mode; grant the security lead `s3:BypassGovernanceRetention`. Place a legal hold on the object versions; remove it when the investigation closes. ## AWS documentation [#aws-documentation] - [Locking objects with Object Lock](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html) - [S3 Glacier Vault Lock](https://docs.aws.amazon.com/amazonglacier/latest/dev/vault-lock.html) # Performance (/docs/s3/performance) ## Baseline performance [#baseline-performance] S3 scales automatically to very high request rates, with first-byte latency of about **100 to 200 ms**. - Your application can reach **at least 3,500 `PUT`/`COPY`/`POST`/`DELETE`** and **11,000 `GET`/`HEAD`** requests **per second per partitioned prefix** in a bucket. - There's **no limit to the number of prefixes** in a bucket. - The prefix is everything between the bucket name and the object name. For example: - `bucket/folder1/sub1/file` → prefix `/folder1/sub1/`; - `bucket/folder1/sub2/file` → prefix `/folder1/sub2/`; - `bucket/1/file` → prefix `/1/`; - `bucket/2/file` → prefix `/2/`. - So spreading reads evenly across four prefixes allows four times the rate: at least **44,000 `GET` requests per second**. - S3 adds capacity to a prefix **gradually** as traffic grows. Too many requests too fast get an HTTP **503 Slow Down** error; retry with backoff. The slides give **5,500** `GET`/`HEAD` requests per second per prefix (so 22,000 across four prefixes). The AWS documentation now says **11,000** per partitioned prefix. Writes are still 3,500. ## Multipart upload [#multipart-upload]
![Multipart upload: a big file is split into parts that are uploaded in parallel, and S3 joins them into one object; a failed part can be retried on its own](/diagrams/s3-multipart-upload.light.svg) ![Multipart upload: a big file is split into parts that are uploaded in parallel, and S3 joins them into one object; a failed part can be retried on its own](/diagrams/s3-multipart-upload.dark.svg)
Split a big file and upload the parts in parallel.
**[Multipart upload](/docs/glossary#term-multipart-upload)** splits one large object into parts: 1. The file is divided into parts (1 to 10,000 parts, each 5 MB to 5 GB, except the last). 2. The parts upload **in parallel**, which speeds up the transfer and uses more of your bandwidth. 3. If one part fails, only that part is retried. 4. When all parts are in, S3 **joins** them into one object. It's **recommended for files over 100 MB** and **required for files over 5 GB**. The AWS CLI and SDKs use it automatically for large files. Parts of uploads that never finish still cost money; a [lifecycle rule](/docs/s3/lifecycle-rules) can delete incomplete multipart uploads. ## S3 Transfer Acceleration [#s3-transfer-acceleration]
![Transfer Acceleration: a file uploaded in the USA goes over a short public internet hop to a nearby CloudFront edge location, then over the fast AWS private network to the bucket in Australia](/diagrams/s3-transfer-acceleration.light.svg) ![Transfer Acceleration: a file uploaded in the USA goes over a short public internet hop to a nearby CloudFront edge location, then over the fast AWS private network to the bucket in Australia](/diagrams/s3-transfer-acceleration.dark.svg)
Enter the AWS network at the nearest edge.
**[S3 Transfer Acceleration](/docs/glossary#term-s3-transfer-acceleration)** speeds up transfers over **long distances**. 1. The client sends the file to the nearest **AWS edge location** (the CloudFront network). That hop over the public internet is short. 2. From the edge, the data travels over the **AWS private network**, which is faster and more reliable than the public internet, to the bucket in its Region. - You turn it on per bucket and use the special endpoint `bucket-name.s3-accelerate.amazonaws.com`. - It works with **multipart upload**. - You pay extra per GB, and only when it actually speeds up the transfer. - The bucket name must not contain dots. ## Byte-range fetches [#byte-range-fetches] A **byte-range fetch** asks for only part of an object, using the HTTP `Range` header. - **Speed up downloads:** request several byte ranges of the same object **in parallel** (part 1, part 2 … part N), like multipart upload in reverse. - **Better resilience:** if one range fails, retry only that range. - **Read only part of a file:** for example, request just the first bytes to read a file's **header**. ## Real-world examples [#real-world-examples] - **A video platform** uploads 20 GB master files with multipart upload, 100 MB parts at a time, in parallel. - **A company in Brazil** sends files to a bucket in Tokyo. Transfer Acceleration cuts upload time noticeably. - **A log processor** reads only the first kilobyte of each large file with a byte-range request, to check its format. - **An analytics job** gets 503 errors because all its keys share one prefix. Spreading keys across many prefixes fixes it. ## Exam tips [#exam-tips] - **"Upload files larger than 5 GB"** → multipart upload (required). **"Faster upload of large files"** → multipart upload. - **"Faster uploads from far away", "users around the world upload to one bucket"** → S3 Transfer Acceleration. - **"Download faster", "read only the beginning of a file"** → byte-range fetches. - **"Higher request rate"** → spread objects across more prefixes. - **"HTTP 503 Slow Down"** → too many requests on one prefix; spread out and retry with backoff. ## Common traps [#common-traps] - **"Transfer Acceleration uses a VPN or Direct Connect."** It uses CloudFront edge locations and the AWS network. - **"S3 request limits are per bucket."** They're per prefix, and there's no limit on prefixes. - **"Multipart upload is only for files over 5 GB."** It's required there, but recommended from 100 MB. ## Hands-on lab: multipart upload and acceleration [#hands-on-lab-multipart-upload-and-acceleration] **Goal:** watch the CLI use multipart upload, and compare with Transfer Acceleration. A 200 MB test file stored briefly in S3 Standard costs **less than a cent**. Transfer Acceleration adds about $0.04 per GB, only when it's faster. Any Region works. ### Upload a big file [#upload-a-big-file] In CloudShell (which has 1 GB of storage), create and upload a 200 MB file: ```bash dd if=/dev/urandom of=big.bin bs=1M count=200 aws s3 cp big.bin s3:///big.bin --debug 2>&1 | grep -c UploadPart ``` The count shows how many `UploadPart` calls the CLI made: it split the file into parts on its own (8 MB parts by default). ### Turn on Transfer Acceleration [#turn-on-transfer-acceleration] Bucket → **Properties → Transfer acceleration → Edit → Enable**. Upload again through the accelerated endpoint: ```bash aws s3 cp big.bin s3:///big2.bin --endpoint-url https://s3-accelerate.amazonaws.com ``` From CloudShell in the same Region you won't see a big difference: acceleration helps over long distances. AWS's [speed comparison tool](https://s3-accelerate-speedtest.s3-accelerate.amazonaws.com/en/accelerate-speed-comparsion.html) shows the effect from your own location. **Expected result:** a large file uploaded in many parts, and acceleration turned on for the bucket. **Clean up:** delete `big.bin` and `big2.bin` from the bucket and from CloudShell (`rm big.bin`), and turn off Transfer Acceleration. ## AWS documentation [#aws-documentation] - [Best practices design patterns: optimizing Amazon S3 performance](https://docs.aws.amazon.com/AmazonS3/latest/userguide/optimizing-performance.html) - [Performance guidelines](https://docs.aws.amazon.com/AmazonS3/latest/userguide/optimizing-performance-guidelines.html) - [Uploading and copying objects using multipart upload](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html) - [Configuring fast, secure file transfers using Transfer Acceleration](https://docs.aws.amazon.com/AmazonS3/latest/userguide/transfer-acceleration.html) # Presigned URLs (/docs/s3/presigned-urls) ## What it is [#what-it-is] A **[presigned URL](/docs/glossary#term-presigned-url)** is a link to one object in a private bucket, signed with someone's AWS credentials, that works **for a limited time**. Anyone holding the link can download (`GET`) or upload (`PUT`) that object, without an AWS account and without making the bucket public. ## How it works [#how-it-works]
![A presigned URL: an owner with access signs a URL and gives it to a customer with no AWS account, who uses it to GET or PUT one object in a private bucket until it expires; the URL carries the owner's permissions and lasts up to 12 hours from the console or up to 7 days from the CLI or SDK](/diagrams/s3-presigned-url.light.svg) ![A presigned URL: an owner with access signs a URL and gives it to a customer with no AWS account, who uses it to GET or PUT one object in a private bucket until it expires; the URL carries the owner's permissions and lasts up to 12 hours from the console or up to 7 days from the CLI or SDK](/diagrams/s3-presigned-url.dark.svg)
A signed link that opens one private object for a while.
1. Someone who has access to the object (the **owner**, or an application) generates a presigned URL with the **S3 console, AWS CLI or an SDK**. Signing happens locally: no call to S3 is needed. 2. They give the URL to a user. 3. The user uses it to `GET` (or `PUT`) the object directly from S3, until the URL **expires**. Users given a presigned URL **inherit the permissions of the identity that generated it**, for that one object and operation. If the signer loses access, the URL stops working. ### How long it lasts [#how-long-it-lasts] - **S3 console:** from 1 minute up to **12 hours** (720 minutes). - **AWS CLI:** set with `--expires-in` in seconds. Default **3,600 seconds** (1 hour), maximum **604,800 seconds** (7 days). - **SDKs:** up to 7 days with an IAM user's credentials. - If the URL is signed with **temporary credentials** (an IAM role), it expires when those credentials expire, even if you asked for longer. ## Examples [#examples] - Let only **logged-in users** download a **premium video**: the app checks the user, then hands out a short-lived URL. - Let an **ever-changing list of users** download files, by generating URLs on the fly instead of managing permissions for each user. - Let a user **temporarily upload a file** to a precise location in your bucket, such as a profile picture, straight from their browser. ## Real-world examples [#real-world-examples] - **A training company** sells video courses. After payment, its site gives each student 15-minute URLs to the videos in a private bucket. - **A mobile app** asks its backend for a presigned `PUT` URL, then uploads photos directly to S3, so large uploads never pass through the backend servers. ## Exam tips [#exam-tips] - **"Give temporary access to a private object without making it public"**, **"users without AWS credentials download one file"** → presigned URL. - **"Let users upload directly to S3 from the browser"** → presigned `PUT` URL. - **"URL stopped working before its expiry time"** → it was signed with temporary credentials that expired, or the signer lost permission. ## Common traps [#common-traps] - **"A presigned URL gives the user their own permissions."** It carries the signer's permissions. - **"Presigned URLs can last a month."** The maximum is 7 days. - **"Make the bucket public for a few days instead."** A presigned URL gives access to one object without exposing the bucket. ## Hands-on lab: share a private object [#hands-on-lab-share-a-private-object] **Goal:** share a private object for five minutes with a presigned URL. A couple of requests cost **less than a cent**. Any Region works. ### Check the object is private [#check-the-object-is-private] Open an object in your private lab bucket and copy its **Object URL**. Open it in a private browser window: **AccessDenied**. ### Create a presigned URL [#create-a-presigned-url] In CloudShell: ```bash aws s3 presign s3:/// --expires-in 300 ``` Open the printed URL in the private window: the object downloads. (In the console, **Object actions → Share with a presigned URL** does the same.) ### Wait for it to expire [#wait-for-it-to-expire] After five minutes, open the URL again: **Request has expired**. **Expected result:** a private object reachable through the signed URL only until it expires. **Clean up:** nothing to delete. ## AWS documentation [#aws-documentation] - [Sharing objects with presigned URLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html) - [Using presigned URLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html) # Requester Pays (/docs/s3/requester-pays) ## What it is [#what-it-is] Normally the **bucket owner pays** for everything about a bucket: the storage, the requests and the data transfer when people download objects. That's a problem when you share a huge dataset with others: every download they make lands on your bill. With a **[Requester Pays](/docs/glossary#term-requester-pays)** bucket, the **requester** pays for the **requests and the data downloaded**, while the owner still pays for **storage**. ## How it works [#how-it-works]
![Who pays: with a normal bucket the owner pays for storage and for every download; with Requester Pays, the owner still pays for storage but the requester, an authenticated AWS account, pays for the requests and the data transfer](/diagrams/s3-requester-pays.light.svg) ![Who pays: with a normal bucket the owner pays for storage and for every download; with Requester Pays, the owner still pays for storage but the requester, an authenticated AWS account, pays for the requests and the data transfer](/diagrams/s3-requester-pays.dark.svg)
Same bucket, different payer for downloads.
- The owner turns on **Requester Pays** in the bucket's properties. - Requesters must be **authenticated in AWS**, so AWS knows whom to bill. **Anonymous access isn't allowed.** - Each request must say the requester accepts the charges: the `x-amz-request-payer: requester` header (or `--request-payer requester` in the CLI). Without it, the request fails. - It's helpful when you want to **share large datasets with other accounts**, such as genomics data, satellite images or public research datasets. If the requester assumes a role in the bucket owner's account, the owner's account pays, since the request comes from the owner's own account. ## Real-world examples [#real-world-examples] - **A research institute** publishes 500 TB of genome data. Universities around the world download it, and each pays for its own transfer. - **A data vendor** shares daily market files with customers' AWS accounts without paying for their downloads. ## Exam tips [#exam-tips] - **"Share a large dataset with other accounts; they should pay for downloads"** → Requester Pays. - **"Requester Pays and anonymous users"** → not allowed; requesters must be authenticated. ## Common traps [#common-traps] - **"Requester Pays makes the requester pay for storage."** The owner still pays storage. - **"Requester Pays for a public website."** Anonymous visitors can't use it. ## Check yourself [#check-yourself] Turning Requester Pays on is one click; testing it properly needs a second AWS account. Instead: Turn on Requester Pays for the bucket. Partners then pay for their requests and downloads, and must send the request-payer header; the company only pays for storage. Requester Pays doesn't allow anonymous requests, and website visitors aren't authenticated AWS users. Serve public content from a bucket without Requester Pays. ## AWS documentation [#aws-documentation] - [Using Requester Pays general purpose buckets](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RequesterPaysBuckets.html) # Security and bucket policies (/docs/s3/security-bucket-policies) ## Two kinds of permission [#two-kinds-of-permission] Access to S3 can be granted in two places: - **User-based: [IAM policies](/docs/identity/users-groups-policies).** Attached to a user, group or role. They say which S3 API calls that identity may make. - **Resource-based:** attached to the bucket or object. - **[Bucket policies](/docs/glossary#term-bucket-policy):** JSON rules on the bucket, set in the S3 console. They can grant access to other accounts and to the public. - **Object ACLs** and **bucket ACLs:** an older, finer-grained system. Since 2023, new buckets have **ACLs disabled** (Object Ownership is *Bucket owner enforced*), and AWS recommends keeping them off. - **Encryption** protects the data itself (see [Encryption](/docs/s3/encryption)). ## How S3 decides [#how-s3-decides]
![How S3 decides: if any policy has an explicit Deny, the request is denied; otherwise it is allowed if an IAM policy or the bucket policy allows it, and denied if nothing allows it](/diagrams/s3-access-decision.light.svg) ![How S3 decides: if any policy has an explicit Deny, the request is denied; otherwise it is allowed if an IAM policy or the bucket policy allows it, and denied if nothing allows it](/diagrams/s3-access-decision.dark.svg)
Deny wins; otherwise one allow is enough.
Within one account, an IAM principal can access an S3 object if: 1. **No policy explicitly denies it** (an explicit `Deny` always wins), **and** 2. **Either** its IAM policy **or** the bucket policy **allows** it. If nothing allows the request, it's denied by default. (Across accounts, both sides must allow; see [cross-account access](/docs/identity/roles-vs-resource-policies).) ## Bucket policies [#bucket-policies] A bucket policy is a JSON document with: - **Resource:** the bucket and/or objects it covers (`arn:aws:s3:::examplebucket/*` is every object). - **Effect:** `Allow` or `Deny`. - **Action:** the API calls, such as `s3:GetObject`. - **Principal:** who it applies to: an account, user, role, service, or `*` (everyone). This policy lets **anyone** read every object, the classic public website policy: ```json { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicRead", "Effect": "Allow", "Principal": "*", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::examplebucket/*"] } ] } ``` Use bucket policies to: - grant **public access** to a bucket; - **force encryption** of objects at upload, or force HTTPS (see [Encryption](/docs/s3/encryption#forcing-encryption-in-transit)); - grant access to **another account** (cross-account). ## Who gets access through what [#who-gets-access-through-what]
![Who gets access through what: an anonymous website visitor through a bucket policy allowing public reads; an IAM user in the same account through an IAM policy; an EC2 instance through an IAM role; a user in another account through the bucket policy](/diagrams/s3-access-examples.light.svg) ![Who gets access through what: an anonymous website visitor through a bucket policy allowing public reads; an IAM user in the same account through an IAM policy; an EC2 instance through an IAM role; a user in another account through the bucket policy](/diagrams/s3-access-examples.dark.svg)
Four ways in, and what lets each one through.
- **Anonymous website visitor** → a **bucket policy** allowing public `GetObject` (and Block Public Access off). - **IAM user in your account** → an **IAM policy** on the user. - **EC2 instance** → an **[IAM role](/docs/identity/roles-and-sts)** attached to the instance. Never put access keys on an instance. - **IAM user in another account** → a **bucket policy** that allows that account (plus an IAM policy on their side). ## Block Public Access [#block-public-access] **[Block Public Access](/docs/glossary#term-block-public-access)** is a safety switch that overrides policies and ACLs to stop data leaks. It has four settings: - block public access granted through **new** ACLs; - block public access granted through **any** ACLs; - block public access granted through **new** public bucket or access point policies; - block public and cross-account access through **any** public bucket or access point policies. All four are **on by default** for new buckets. If a bucket should never be public, leave them on. They can also be set for the **whole account** or for every account in an **organization**, which beats any bucket setting. ## Real-world examples [#real-world-examples] - **A company leaks customer files** because someone made a bucket public. Turning on Block Public Access at the account level would have stopped it, whatever the bucket policy said. - **An app on EC2** reads images from a private bucket through its instance role, with no keys stored anywhere. - **A partner company** gets read access to one prefix of a bucket through the bucket policy, naming the partner's account ID as the principal. ## Exam tips [#exam-tips] - **"Give an EC2 instance access to S3"** → IAM role (instance profile), not access keys. - **"Grant access to another AWS account"** → bucket policy (cross-account). - **"Make objects publicly readable"** → bucket policy with `Principal: "*"` and Block Public Access off. - **"Prevent any bucket in the account from ever being public"** → Block Public Access at the account (or organization) level. - **"Explicit deny in a bucket policy vs allow in IAM"** → deny wins. ## Common traps [#common-traps] - **"Use ACLs to manage access."** ACLs are disabled by default; use policies. - **"A bucket policy allows public read, so it's public."** Not if Block Public Access is on. - **"An IAM allow overrides a bucket policy deny."** An explicit deny always wins. ## Hands-on lab: a bucket policy and Block Public Access [#hands-on-lab-a-bucket-policy-and-block-public-access] **Goal:** try to make one object public, see Block Public Access stop it, then allow it. A few requests and one small object cost **less than a cent**. Any Region works. **Before you start:** use the bucket and image from the [first bucket lab](/docs/s3#hands-on-lab-your-first-bucket). ### Try the public URL [#try-the-public-url] Open the object and copy its **Object URL**. Open it in a private browser window: **AccessDenied**. The bucket is private. ### Try to add a public policy [#try-to-add-a-public-policy] Bucket → **Permissions → Bucket policy → Edit**. Paste the public-read policy above, changing `examplebucket` to your bucket name and the resource to `arn:aws:s3:::/photos/*`. Save: S3 refuses, because Block Public Access is on. ### Turn off Block Public Access for this bucket [#turn-off-block-public-access-for-this-bucket] **Permissions → Block public access → Edit**, untick **Block all public access**, confirm. Save the bucket policy again: it works now. Reload the Object URL: the image loads. **Expected result:** the object is only public once both the bucket policy allows it and Block Public Access is off. **Clean up:** delete the bucket policy and turn **Block all public access** back on. ## AWS documentation [#aws-documentation] - [Policies and permissions in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-policy-language-overview.html) - [Examples of bucket policies](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html) - [Controlling ownership of objects and disabling ACLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/about-object-ownership.html) - [Blocking public access to your Amazon S3 storage](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-control-block-public-access.html) # Static website hosting (/docs/s3/static-website) ## What it is [#what-it-is] A **static website** is made of files that don't change per visitor: HTML, CSS, JavaScript and images. S3 can serve such a site directly from a bucket and make it reachable on the internet, with no web server to run. (Pages built on a server per request, such as PHP, need EC2, containers or Lambda instead.) ## How it works [#how-it-works]
![Static website hosting: visitors browse to the bucket website endpoint over HTTP, and S3 returns index.html and error.html; Block Public Access must be off and a bucket policy must allow public GetObject](/diagrams/s3-static-website.light.svg) ![Static website hosting: visitors browse to the bucket website endpoint over HTTP, and S3 returns index.html and error.html; Block Public Access must be off and a bucket policy must allow public GetObject](/diagrams/s3-static-website.dark.svg)
A bucket serving a website to the internet.
1. You turn on **Static website hosting** for the bucket and name an **index document** (`index.html`) and optionally an **error document** (`error.html`). 2. S3 gives the bucket a **website endpoint**. Depending on the Region, it looks like either: - `http://bucket-name.s3-website-aws-region.amazonaws.com`, or - `http://bucket-name.s3-website.aws-region.amazonaws.com`. 3. Visitors' browsers request pages from that endpoint, and S3 returns the files. For this to work, the objects must be **publicly readable**: turn off Block Public Access for the bucket and add a [bucket policy](/docs/s3/security-bucket-policies#bucket-policies) that allows `s3:GetObject` to everyone. **If you get a `403 Forbidden` error**, the bucket policy doesn't allow public reads (or Block Public Access is still on). ## HTTPS and custom domains [#https-and-custom-domains] - **Website endpoints only speak HTTP.** They don't support HTTPS. - For HTTPS, put **Amazon CloudFront** in front of the bucket (see [CloudFront](/docs/edge/cloudfront)). CloudFront can also keep the bucket private, using origin access control, so you don't need public access at all. AWS also suggests **AWS Amplify Hosting** for simple sites. - A bucket encrypted with **SSE-KMS** can't serve anonymous visitors through the website endpoint; use CloudFront. - For your own domain name (`www.example.com`), use **Route 53** with CloudFront, or a bucket named exactly like the domain. ## Real-world examples [#real-world-examples] - **A product launch page** is a few HTML files and images in a bucket. It costs pennies and survives any traffic spike. - **A single-page app** (React, Vue) is built into static files, stored in S3 and served worldwide over HTTPS through CloudFront. ## Exam tips [#exam-tips] - **"Host a static website cheaply with no servers"** → S3 static website hosting. - **"403 Forbidden on the S3 website"** → add a bucket policy allowing public `s3:GetObject` (and turn off Block Public Access). - **"Static website with HTTPS"** → CloudFront in front of S3. - **"Website with server-side code"** → not S3 alone; use compute. ## Common traps [#common-traps] - **"Enable HTTPS on the S3 website endpoint."** Not supported; use CloudFront. - **"Static website hosting makes objects public."** You still need the bucket policy. ## Hands-on lab: a website in a bucket [#hands-on-lab-a-website-in-a-bucket] **Goal:** host a one-page website from S3. A few small files and requests cost **less than a cent**. Any Region works. ### Create the bucket and files [#create-the-bucket-and-files] Create a bucket `saa-site-` in us-east-1 with tag `Project=saa-lab`. On your computer, create `index.html` containing `

Hello from S3

` and `error.html` containing `

Not found

`. Upload both.
### Turn on website hosting [#turn-on-website-hosting] Bucket → **Properties → Static website hosting → Edit → Enable**. Index document `index.html`, error document `error.html`. Save, and copy the **Bucket website endpoint** at the bottom of Properties. ### Open it, see 403, then fix it [#open-it-see-403-then-fix-it] Open the endpoint: **403 Forbidden**. Now **Permissions → Block public access → Edit**, untick everything, confirm. Add a bucket policy allowing `s3:GetObject` on `arn:aws:s3:::saa-site-/*` to `"Principal": "*"` (as on the [bucket policies page](/docs/s3/security-bucket-policies#bucket-policies)). Reload: "Hello from S3". Try `/missing.html`: your error page.
**Expected result:** a public website served over HTTP from your bucket's website endpoint. **Clean up:** empty and delete the `saa-site-` bucket. ## AWS documentation [#aws-documentation] - [Hosting a static website using Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html) - [Website endpoints](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteEndpoints.html) # Storage classes (/docs/s3/storage-classes) ## What it is [#what-it-is] Every S3 object has a **storage class**. They all keep your data equally safe, but trade **storage price** against **access price, speed and availability**. Hot data that's read all the time belongs in S3 Standard; old data you may never read belongs in Glacier Deep Archive, at a fraction of the price. You can set the class when you upload, change it later, or let [lifecycle rules](/docs/s3/lifecycle-rules) move objects automatically. ## Durability and availability [#durability-and-availability] - **Durability** is how unlikely you are to **lose** an object. S3 is designed for **99.999999999% (eleven 9s)** durability across multiple AZs. If you store 10 million objects, you'd expect to lose one about once every 10,000 years. It's the **same for all storage classes** (except One Zone classes lose data if their AZ is destroyed). - **Availability** is how often you can **reach** the data. It varies by class. S3 Standard is designed for **99.99%**, roughly 53 minutes a year when it might not be available. ## The storage classes [#the-storage-classes]
![The S3 storage classes from hottest to coldest, with how many AZs hold the data, the minimum storage duration and the time to first byte: Express One Zone, Standard, Intelligent-Tiering, Standard-IA, One Zone-IA, Glacier Instant Retrieval, Glacier Flexible Retrieval and Glacier Deep Archive](/diagrams/s3-storage-classes.light.svg) ![The S3 storage classes from hottest to coldest, with how many AZs hold the data, the minimum storage duration and the time to first byte: Express One Zone, Standard, Intelligent-Tiering, Standard-IA, One Zone-IA, Glacier Instant Retrieval, Glacier Flexible Retrieval and Glacier Deep Archive](/diagrams/s3-storage-classes.dark.svg)
From hot and fast to cold and cheap.
### S3 Standard (general purpose) [#s3-standard-general-purpose] - **99.99% availability.** For **frequently accessed** data. - Low latency and high throughput. Survives **two** concurrent facility failures. - No minimum duration and no retrieval fee. - **Use cases:** big data analytics, mobile and gaming apps, content distribution. ### Infrequent Access classes [#infrequent-access-classes] For data that's read **less often** but must be available **immediately** when it is. Cheaper storage than Standard, but you pay a **retrieval fee per GB**, a **30-day minimum** storage charge, and a minimum billable size of **128 KB**. - **[S3 Standard-IA](/docs/glossary#term-s3-standard-ia):** **99.9%** availability, stored across multiple AZs. **Use cases:** disaster recovery copies, backups. - **S3 One Zone-IA:** stored in **one AZ**: still eleven 9s durability within that AZ, but **data is lost if the AZ is destroyed**. **99.5%** availability, and cheaper. **Use cases:** secondary copies of on-premises backups, or data you can **re-create**. ### Glacier classes [#glacier-classes] Low-cost storage for **archives and backups**. You pay for storage plus a **retrieval** cost. - **[S3 Glacier Instant Retrieval](/docs/glossary#term-s3-glacier):** **milliseconds** to retrieve. For data read about **once a quarter**. **90-day** minimum. - **S3 Glacier Flexible Retrieval** (formerly S3 Glacier): data is archived, so you **restore** it first: - **Expedited:** 1 to 5 minutes; - **Standard:** 3 to 5 hours; - **Bulk:** 5 to 12 hours, and **free**. - **90-day** minimum. - **S3 Glacier Deep Archive:** the cheapest, for **long-term** storage: - **Standard:** within 12 hours; - **Bulk:** within 48 hours. - **180-day** minimum. ### S3 Intelligent-Tiering [#s3-intelligent-tiering]
![S3 Intelligent-Tiering moves each object between access tiers by itself: Frequent Access, then Infrequent Access after 30 days without a read, then Archive Instant Access after 90 days; optional Archive Access and Deep Archive Access tiers take objects after 90 to 730 and 180 to 730 days, with restores taking hours; there are no retrieval fees, a small monitoring fee, and reading an object moves it back to Frequent Access](/diagrams/s3-intelligent-tiering.light.svg) ![S3 Intelligent-Tiering moves each object between access tiers by itself: Frequent Access, then Infrequent Access after 30 days without a read, then Archive Instant Access after 90 days; optional Archive Access and Deep Archive Access tiers take objects after 90 to 730 and 180 to 730 days, with restores taking hours; there are no retrieval fees, a small monitoring fee, and reading an object moves it back to Frequent Access](/diagrams/s3-intelligent-tiering.dark.svg)
S3 watches each object and moves it for you.
**[S3 Intelligent-Tiering](/docs/glossary#term-s3-intelligent-tiering)** is for data whose access pattern is **unknown or changing**. - A small monthly **monitoring and automation fee** per object. **No retrieval fees.** - S3 moves each object between **access tiers** based on use: - **Frequent Access** (automatic): the default tier. - **Infrequent Access** (automatic): objects not read for **30 days**. - **Archive Instant Access** (automatic): objects not read for **90 days**. - **Archive Access** (optional): configurable from **90 to 730 days**. - **Deep Archive Access** (optional): configurable from **180 to 730 days**. - Reading an object moves it back to Frequent Access. Objects smaller than 128 KB aren't monitored and stay in Frequent Access. ### S3 Express One Zone [#s3-express-one-zone] **[S3 Express One Zone](/docs/glossary#term-s3-express-one-zone)** is a **high-performance** class in a **single AZ**. - Objects live in a **directory bucket**, a special bucket type in one AZ (its name includes the AZ ID, such as `my-data--use1-az4--x-s3`). - Handles **hundreds of thousands of requests per second** with **single-digit millisecond** latency: up to **10× faster** than S3 Standard, with request costs **80% lower**. - Eleven 9s durability and **99.95%** availability, within the AZ. - **Co-locate** storage with your compute in the same AZ to cut latency. - **Use cases:** latency-sensitive and data-intensive apps, AI and ML training, financial modelling, media processing, HPC. Works well with SageMaker AI model training, Athena, EMR and Glue. The slides say Express One Zone has **50% lower** request costs than S3 Standard. After later price cuts, the AWS documentation now says **80% lower**. ## Comparing the classes [#comparing-the-classes] | Class | Availability | Minimum | | --- | --- | --- | | Standard | 99.99% | none | | Intelligent-Tiering | 99.9% | none | | Standard-IA | 99.9% | 30 days | | One Zone-IA | 99.5% | 30 days | | Glacier Instant | 99.9% | 90 days | | Glacier Flexible | 99.99% | 90 days | | Deep Archive | 99.99% | 180 days | Storage prices in us-east-1 fall from about **$0.023 per GB-month** for Standard to about **$0.00099** for Deep Archive, while retrieval gets slower and more expensive. Check the [S3 pricing page](https://aws.amazon.com/s3/pricing/) for current numbers. ## Real-world examples [#real-world-examples] - **A photo-sharing app** keeps new photos in Standard; after 30 days few are viewed, so they move to Standard-IA. - **A bank** must keep statements for 10 years and almost never reads them. They go to Glacier Deep Archive; a rare request can wait 12 hours. - **A data lake** with unpredictable queries uses Intelligent-Tiering, so nobody has to guess which data is hot. - **An ML team** puts training data in Express One Zone in the same AZ as its GPU instances, so training isn't waiting on storage. ## Exam tips [#exam-tips] - **"Frequently accessed"** → Standard. **"Unknown or changing access patterns"** → Intelligent-Tiering. - **"Infrequent but needs immediate access", "backups, DR"** → Standard-IA. - **"Can be re-created", "secondary copy", "cheapest immediate access"** → One Zone-IA. - **"Archive, read once a quarter, milliseconds"** → Glacier Instant Retrieval. - **"Archive, retrieval in minutes or hours"** → Glacier Flexible Retrieval (Expedited 1–5 min, Bulk free). - **"Cheapest storage, retrieval within 12 or 48 hours", "keep for years for compliance"** → Glacier Deep Archive. - **"Single-digit millisecond, very high request rate, same AZ as compute"** → S3 Express One Zone. ## Common traps [#common-traps] - **"Glacier Flexible Retrieval for data needed within milliseconds."** It must be restored first; use Glacier Instant Retrieval. - **"One Zone-IA for the only copy of important data."** It's lost if the AZ is destroyed. - **"Store objects in Standard-IA for a week."** You pay the 30-day minimum anyway. - **"Durability differs between classes."** It's eleven 9s for all of them; availability differs. ## Hands-on lab: change an object's storage class [#hands-on-lab-change-an-objects-storage-class] **Goal:** upload an object straight into a cheaper class, then move it. A small object in Standard-IA is billed as 128 KB for 30 days: **far less than a cent**. Any Region works. ### Upload into Standard-IA [#upload-into-standard-ia] In your lab bucket, **Upload** a file, open **Properties** in the upload page, choose storage class **Standard-IA**, and upload. ### Change the class [#change-the-class] Select the object → **Actions → Edit storage class** → **Glacier Instant Retrieval** → Save. The object list shows the new class. ### Try a CLI upload [#try-a-cli-upload] In CloudShell: ```bash echo hello > a.txt aws s3 cp a.txt s3:///a.txt --storage-class INTELLIGENT_TIERING ``` The object appears with storage class **Intelligent-Tiering**. **Expected result:** objects in three different classes in the same bucket. **Clean up:** delete the objects you uploaded. ## AWS documentation [#aws-documentation] - [Understanding and managing Amazon S3 storage classes](https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage-class-intro.html) - [How S3 Intelligent-Tiering works](https://docs.aws.amazon.com/AmazonS3/latest/userguide/intelligent-tiering-overview.html) - [S3 Express One Zone](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-one-zone.html) - [Understanding archive retrieval options](https://docs.aws.amazon.com/AmazonS3/latest/userguide/restoring-objects-retrieval-options.html) - [Amazon S3 pricing](https://aws.amazon.com/s3/pricing/) # Versioning and replication (/docs/s3/versioning-replication) ## Versioning [#versioning]
![Versioning keeps every version of one key: the object uploaded before versioning has version null; each PUT adds a new version; a DELETE adds a delete marker that becomes the current version, so GET returns 404 while older versions can still be restored](/diagrams/s3-versioning.light.svg) ![Versioning keeps every version of one key: the object uploaded before versioning has version null; each PUT adds a new version; a DELETE adds a delete marker that becomes the current version, so GET returns 404 while older versions can still be restored](/diagrams/s3-versioning.dark.svg)
Every overwrite and delete leaves the old version behind.
**[Versioning](/docs/glossary#term-s3-versioning)** keeps every version of an object. - It's turned on at the **bucket level**. A bucket is unversioned (the default), versioning-enabled or versioning-suspended. - Uploading to the **same key** doesn't overwrite: it adds a **new version**, each with its own version ID (in practice a long random string; the diagram numbers them for clarity). - **Deleting** an object without a version ID doesn't remove anything: S3 adds a **delete marker**, which becomes the current version. `GET` now returns 404, but the older versions are still there. Delete the marker and the object is back. - Deleting **a specific version ID** removes that version permanently. Why it's best practice: - protects against **accidental deletes and overwrites** (restore an older version); - makes it easy to **roll back** to a previous version. Notes: - Objects stored **before** versioning was turned on have the version ID **`null`**. - **Suspending** versioning doesn't delete existing versions; new uploads just stop creating versions. - Versioning **can't be turned off** once enabled, only suspended. - Every version is stored and billed. Use [lifecycle rules](/docs/s3/lifecycle-rules) to expire old versions. ## Replication [#replication]
![S3 replication: a source bucket in eu-west-1 copies new objects asynchronously to a bucket in the same Region (Same-Region Replication) and to a bucket in us-east-1 (Cross-Region Replication), which can be in another account; versioning must be on in both buckets](/diagrams/s3-replication.light.svg) ![S3 replication: a source bucket in eu-west-1 copies new objects asynchronously to a bucket in the same Region (Same-Region Replication) and to a bucket in us-east-1 (Cross-Region Replication), which can be in another account; versioning must be on in both buckets](/diagrams/s3-replication.dark.svg)
Copy new objects to another bucket automatically.
**[S3 Replication](/docs/glossary#term-s3-replication)** copies objects from a source bucket to one or more destination buckets automatically. - **Cross-Region Replication (CRR):** the destination is in **another Region**. - **Same-Region Replication (SRR):** the destination is in the **same Region**. - **Versioning must be on** in both the source and destination buckets. - Buckets can be in **different AWS accounts**. - Copying is **asynchronous**: it usually takes seconds, but there's no guarantee. **S3 Replication Time Control (RTC)** promises 99.9% of objects within **15 minutes**, for a fee. - S3 needs an **IAM role** that lets it read the source and write the destination. Use cases: - **CRR:** compliance (a copy far away), **lower-latency** access for users in another Region, replication **across accounts**. - **SRR:** **log aggregation** from several buckets into one, live replication between **production and test** accounts. ### What gets replicated [#what-gets-replicated] - After you turn on replication, **only new objects** are replicated. - To copy **existing objects**, and objects that **failed** to replicate, use **[S3 Batch Replication](/docs/s3/batch-operations-storage-lens)**. - **Deletes:** - **Delete markers** can be replicated, if you turn that option on. - **Deletes of a specific version** are **never** replicated, so a malicious delete in the source can't wipe the copy. - **No chaining:** if bucket 1 replicates to bucket 2, and bucket 2 replicates to bucket 3, objects created in bucket 1 are **not** copied on to bucket 3. Replicas aren't replicated again. - **Two-way replication** between two buckets is possible, for active-active setups. ## Real-world examples [#real-world-examples] - **A hospital** keeps patient images in eu-west-1 and replicates them with CRR to eu-central-1, to meet a rule that a copy must be in a second location. - **A company** collects application logs from ten buckets into one central bucket with SRR, for analysis. - **A developer overwrites `config.json` with a broken version.** With versioning on, they restore the previous version in seconds. ## Exam tips [#exam-tips] - **"Protect against accidental deletion or overwrite"** → versioning (plus MFA Delete for more protection). - **"Restore a deleted object"** → delete the delete marker (or copy the previous version). - **"Copy objects to another Region automatically", "disaster recovery for S3"** → CRR. - **"Aggregate logs from many buckets in the same Region"** → SRR. - **"Replicate objects that existed before replication was turned on"** → S3 Batch Replication. - **"Replication within a guaranteed time"** → S3 Replication Time Control. ## Common traps [#common-traps] - **"Turn on replication without versioning."** Both buckets need versioning. - **"Replication copies existing objects."** Only new ones; use Batch Replication for the rest. - **"A → B and B → C means A's objects reach C."** Replication doesn't chain. - **"Suspending versioning deletes old versions."** It doesn't. ## Hands-on lab: versioning and a delete marker [#hands-on-lab-versioning-and-a-delete-marker] **Goal:** turn on versioning, overwrite and delete a file, and get it back. A few versions of a small file cost **less than a cent**. Any Region works. ### Turn on versioning [#turn-on-versioning] Use your lab bucket. **Properties → Bucket Versioning → Edit → Enable**. Upload a text file `note.txt` containing `v1`. ### Overwrite and delete [#overwrite-and-delete] Change the file to `v2` and upload it again with the same name. Then select `note.txt` and **Delete** it (type `delete` to confirm). The object list is empty. ### Show versions and restore [#show-versions-and-restore] Turn on **Show versions**. You see two versions of `note.txt` and a **Delete marker** on top. Select the delete marker and delete it (**permanently delete**). Turn off Show versions: `note.txt` is back, with `v2` inside. **Expected result:** a "deleted" file restored by removing its delete marker, with older versions still available. **Clean up:** with Show versions on, delete every version of `note.txt`. Keep versioning on if you'll do the replication or lifecycle labs. ## AWS documentation [#aws-documentation] - [Retaining multiple versions of objects with S3 Versioning](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html) - [Replicating objects within and across Regions](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html) - [What does Amazon S3 replicate?](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication-what-is-isnot-replicated.html) - [Replicating existing objects with Batch Replication](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-batch-replication-batch.html) - [Meeting compliance requirements with S3 Replication Time Control](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication-time-control.html) # Application Load Balancer (/docs/scaling/alb) ## What it is [#what-it-is] The **[Application Load Balancer](/docs/glossary#term-application-load-balancer)** (ALB) works at **layer 7**, the HTTP level. Because it understands HTTP requests, it can route each one by its content: - load balance to **many HTTP applications** across machines (target groups); - load balance to **many applications on the same machine**, such as containers on different ports; - supports **HTTP/2**, **WebSocket** and **gRPC**; - **redirects**, for example HTTP to HTTPS, and **fixed responses** without touching a server; - can **authenticate users** (Cognito or any OpenID Connect provider) before requests reach your app. ## Routing to target groups [#routing-to-target-groups]
![The ALB's listener rules send /users* to target group A, /search* to target group B, and ?p=desktop to target group C of on-premises servers registered by IP](/diagrams/scaling-alb-routing.light.svg) ![The ALB's listener rules send /users* to target group A, /search* to target group B, and ?p=desktop to target group C of on-premises servers registered by IP](/diagrams/scaling-alb-routing.dark.svg)
One load balancer, several applications.
Each listener has **rules**, checked in priority order. A rule has **conditions** and an **action**. Conditions can match: - the **path** in the URL: `example.com/users` vs `example.com/posts`; - the **hostname**: `one.example.com` vs `other.example.com`; - the **query string**: `example.com/users?id=123&order=false`; - **HTTP headers**, the **HTTP method** (GET, POST) and the **source IP**. Actions are **forward** (to one target group, or split by weight between several, handy for blue/green deployments), **redirect**, **fixed response**, and **authenticate**. Each listener also has a **default rule** for requests no other rule matches. This makes ALBs a great fit for **microservices and containers** (Docker, Amazon ECS): one ALB serves many services. ECS uses **dynamic port mapping**, so many containers on one instance each register on their own port. With Classic Load Balancers you'd need one load balancer per application. ### Target groups [#target-groups] An ALB target group can contain: - **EC2 instances** (often managed by an Auto Scaling group), over HTTP or HTTPS; - **ECS tasks** (registered by ECS itself); - **Lambda functions**: the HTTP request becomes a JSON event; - **IP addresses**, which must be private IPs (for example on-premises servers reached over VPN or Direct Connect). One ALB can route to many target groups, and **health checks are set per target group**. The default routing algorithm is round robin; *least outstanding requests* sends each request to the least busy target. ## Good to know: the client's IP [#good-to-know-the-clients-ip]
![The client at 12.34.56.78 connects to the ALB, which opens a new connection to the instance from 10.0.1.25 and adds X-Forwarded-For: 12.34.56.78](/diagrams/scaling-alb-xff.light.svg) ![The client at 12.34.56.78 connects to the ALB, which opens a new connection to the instance from 10.0.1.25 and adds X-Forwarded-For: 12.34.56.78](/diagrams/scaling-alb-xff.dark.svg)
The real client IP travels in a header.
- An ALB has a **fixed DNS name** (`name-123.region.elb.amazonaws.com`), but **no static IP addresses**: point Route 53 or a CNAME at the name. - It **terminates** the client's connection and opens a new one to the target. The application sees the **ALB's private IP** as the source. - The client's real IP is in the **`X-Forwarded-For`** header, with the port in `X-Forwarded-Port` and the protocol in `X-Forwarded-Proto`. ALBs now also support **gRPC**, routing by **HTTP method and source IP**, **weighted** forwarding between target groups, **mutual TLS** (clients present certificates too), and **JWT verification** of tokens at the load balancer. The core ideas in the slides are unchanged. ## Exam tips [#exam-tips] - **"Route by URL path / hostname / query string / header"** → ALB listener rules. - **"Microservices or containers behind one load balancer"**, **"ECS dynamic ports"** → ALB. - **"Invoke a Lambda function over HTTP from a load balancer"** → ALB with a Lambda target group. - **"Redirect HTTP to HTTPS"** → ALB redirect action. - **"The application needs the client's IP address"** → read `X-Forwarded-For`. - **"Static IP for an ALB"** → put an NLB in front with the ALB as its target, or use Global Accelerator. ## Common traps [#common-traps] - **"Give the ALB an Elastic IP."** ALBs don't support Elastic IPs. - **"The app logs show the client IP as the source."** They show the ALB's IP unless you log `X-Forwarded-For`. - **"Use an ALB for UDP traffic."** ALB is HTTP/HTTPS only; UDP needs an NLB. ## Hands-on lab: route by query string and return a fixed response [#hands-on-lab-route-by-query-string-and-return-a-fixed-response] **Goal:** add listener rules that route some requests to a different target group and answer others without any server. Uses `saa-alb` and the two instances from the [Elastic Load Balancing lab](/docs/scaling/elb-overview#hands-on-lab-two-web-servers-behind-an-alb), under $0.10 an hour. Delete everything at the end. ### Make a second target group [#make-a-second-target-group] Create target group `saa-tg-2` (instances, HTTP 80) and register **only** `saa-web-2`. ### Add a query-string rule [#add-a-query-string-rule] Open `saa-alb` → **Listeners → HTTP:80 → Manage rules → Add rule**: name `two`, condition **Query string** key `who`, value `two`, action **Forward** to `saa-tg-2`, priority 10. Save. ### Add a fixed-response rule [#add-a-fixed-response-rule] Add another rule: condition **Path** is `/health-page`, action **Return fixed response**, code 200, content type `text/plain`, body `ALB is up`. Priority 20. ### Test [#test] Browse to: - `http:///`: alternates between both instances (the default rule); - `http:///?who=two`: always shows `saa-web-2`'s hostname, however often you refresh; - `http:///health-page`: the text *ALB is up*, served by the load balancer itself. **Expected result:** the default rule balances between both instances, `?who=two` always reaches one target group, and `/health-page` is answered by the load balancer alone. **Clean up:** delete `saa-alb`, then both target groups, terminate both instances, and delete `saa-alb-sg`. ## AWS documentation [#aws-documentation] - [What is an Application Load Balancer?](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html) - [Listener rules: condition types](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/rule-condition-types.html) - [Target groups for your Application Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html) - [X-Forwarded headers](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/x-forwarded-headers.html) # Auto Scaling groups (/docs/scaling/auto-scaling-groups) ## What it is [#what-it-is] Real traffic goes up and down: busy in the day, quiet at night, huge on sale days. In the cloud you can create and remove servers in minutes, so you shouldn't pay for peak capacity all the time. An **[Auto Scaling group](/docs/glossary#term-auto-scaling-group)** (ASG) manages a fleet of EC2 instances for you. It can: - **scale out** (add instances) when the load increases; - **scale in** (remove instances) when the load decreases; - keep the number of instances between a **minimum** and a **maximum**; - **register** new instances with a load balancer automatically; - **replace** an instance that fails or is terminated. **Auto Scaling groups are free.** You pay only for the EC2 instances (and other resources) they run. ## Capacity: minimum, desired, maximum [#capacity-minimum-desired-maximum]
![An Auto Scaling group with a minimum of 2 instances, a desired capacity of 4 running now, and room to scale out to a maximum of 7](/diagrams/scaling-asg-capacity.light.svg) ![An Auto Scaling group with a minimum of 2 instances, a desired capacity of 4 running now, and room to scale out to a maximum of 7](/diagrams/scaling-asg-capacity.dark.svg)
The three numbers that size a group.
- **Minimum:** the group never goes below this, even with no load. Here, 2. - **Desired:** how many it runs right now. Scaling policies (or you) change this number. Here, 4. - **Maximum:** the ceiling, which also caps your bill. Here, 7. If an instance dies, the group launches a new one to get back to the desired number. ## With a load balancer, across AZs [#with-a-load-balancer-across-azs]
![Users reach an ALB that health-checks instances in two AZs; the Auto Scaling group adds new instances to the target group and replaces failed ones](/diagrams/scaling-asg-elb.light.svg) ![Users reach an ALB that health-checks instances in two AZs; the Auto Scaling group adds new instances to the target group and replaces failed ones](/diagrams/scaling-asg-elb.dark.svg)
The standard highly available web tier.
1. The group spreads instances **evenly across the AZs** (subnets) you give it, and rebalances if one AZ ends up with more. 2. It **registers** every new instance with the load balancer's **target group**, and deregisters instances it removes. 3. The load balancer sends traffic only to healthy instances. 4. If you turn on **ELB health checks** for the group, an instance the load balancer marks unhealthy is **terminated and replaced**. ### Health checks [#health-checks] - **EC2 status checks** are always used: a stopped or impaired instance is replaced. - **ELB health checks** (optional, recommended behind a load balancer) also replace instances whose application fails the target group's health check. - A **health check grace period** gives new instances time to boot before they're judged. ## What a group needs [#what-a-group-needs]
![A launch template holds the AMI, instance type, user data, EBS volumes, security groups, key pair, IAM role and network settings; the group adds min, desired and max, subnets and AZs, target group, health checks and scaling policies](/diagrams/scaling-launch-template.light.svg) ![A launch template holds the AMI, instance type, user data, EBS volumes, security groups, key pair, IAM role and network settings; the group adds min, desired and max, subnets and AZs, target group, health checks and scaling policies](/diagrams/scaling-launch-template.dark.svg)
How to launch an instance, and how many to run.
- A **[launch template](/docs/glossary#term-launch-template)** says **how to launch each instance**: AMI and instance type, user data, EBS volumes, security groups, SSH key pair, IAM role (instance profile), network and subnet settings. Launch templates have **versions**, so you can change them safely. - The **group's own settings** say **how many and where**: min, desired and max size, subnets (and so AZs), load balancer target groups, health checks, and [scaling policies](/docs/scaling/scaling-policies). - A group can also mix **instance types** and **On-Demand with Spot** (a *mixed instances policy*), which is a cheap and resilient way to run fault-tolerant work. The older **launch configurations** are on their way out. They haven't supported instance types released since 1 January 2023, and accounts created on or after **1 October 2024 can't create them at all**. Use launch templates. ## Exam tips [#exam-tips] - **"Automatically replace failed instances"**, **"maintain a fixed number of instances"** → Auto Scaling group (even with min = max). - **"Replace instances the load balancer marks unhealthy"** → turn on ELB health checks for the group. - **"Highly available across AZs"** → the group's subnets span at least two AZs. - **"Change the AMI or instance type for new instances"** → a new launch template version (then an [instance refresh](/docs/scaling/scaling-policies#instance-refresh) to replace existing ones). - **"Cheapest for fault-tolerant work, keep a baseline"** → mixed instances policy with On-Demand base capacity plus Spot. ## Common traps [#common-traps] - **"Auto Scaling groups cost extra."** They're free. - **"Edit the launch configuration to change instances."** Launch configurations can't be edited; and you should use launch templates anyway. - **"The group replaces instances that fail the ALB health check by default."** Only EC2 status checks by default; ELB health checks must be turned on. ## Hands-on lab: a self-healing group behind an ALB [#hands-on-lab-a-self-healing-group-behind-an-alb] **Goal:** create a launch template and an Auto Scaling group of two instances behind an ALB, then terminate one and watch it come back. Two `t3.micro` instances, an ALB and its public IPs: under **$0.10 an hour**. At the end, delete the group (which terminates its instances) and the load balancer. ### Create a launch template [#create-a-launch-template] **EC2 → Launch templates → Create launch template**: name `saa-lt`, tick **Auto Scaling guidance**, Amazon Linux 2023, `t3.micro`, key pair `saa-lab-key`, security group `saa-web-sg`, and paste the web server script from the [EC2 basics lab](/docs/compute/ec2-basics#user-data-bootstrapping-an-instance) into **Advanced details → User data**. Create. ### Create the group with a load balancer [#create-the-group-with-a-load-balancer] **Auto Scaling groups → Create**: name `saa-asg`, template `saa-lt`. Choose the default VPC and **two or more subnets**. Choose **Attach to a new load balancer** → Application Load Balancer, internet-facing, listener HTTP 80, **create a target group** `saa-asg-tg`. Turn on **Elastic Load Balancing health checks**. Group size: desired **2**, min **2**, max **4**. No scaling policy yet. Tag `Project=saa-lab` and create. ### Test it [#test-it] When both instances are *InService* and healthy in the target group, open the new ALB's DNS name and refresh: the two hostnames alternate. (If the page doesn't load, make sure `saa-web-sg` allows HTTP from the ALB's security group or from anywhere.) ### Break it [#break-it] In **Instances**, terminate one of the group's instances. Open the group's **Activity** tab: within a minute or two it launches a replacement, which registers with the target group and starts serving. **Expected result:** the group always returns to its desired capacity of 2, by itself. **Clean up:** keep the group for the [scaling policies lab](/docs/scaling/scaling-policies#hands-on-lab-scale-on-cpu-with-target-tracking), or delete the Auto Scaling group (this terminates its instances), then the load balancer, the target group and the launch template. ## AWS documentation [#aws-documentation] - [What is Amazon EC2 Auto Scaling?](https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html) - [Launch templates for Auto Scaling groups](https://docs.aws.amazon.com/autoscaling/ec2/userguide/launch-templates.html) - [Auto Scaling launch configurations](https://docs.aws.amazon.com/autoscaling/ec2/userguide/launch-configurations.html) - [Health checks for instances in an Auto Scaling group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-health-checks.html) - [Use Elastic Load Balancing to distribute traffic in an Auto Scaling group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html) # Elastic Load Balancing (/docs/scaling/elb-overview) ## What it is [#what-it-is] A **load balancer** is a server that receives requests and forwards them to several servers behind it (the *targets*), such as EC2 instances. **[Elastic Load Balancing](/docs/glossary#term-elastic-load-balancing)** (ELB) is AWS's managed load balancer service.
![Users reach one load balancer by DNS name; it sends requests to two healthy EC2 instances and none to the instance that failed its health check](/diagrams/scaling-elb.light.svg) ![Users reach one load balancer by DNS name; it sends requests to two healthy EC2 instances and none to the instance that failed its health check](/diagrams/scaling-elb.dark.svg)
One entry point, several targets.
## Why use a load balancer [#why-use-a-load-balancer] - **Spread the load** across many instances. - **One point of access**, a DNS name, for the whole application, however many instances there are. - **Handle failures smoothly:** traffic goes only to healthy instances. - **Health checks** on every instance. - **SSL/TLS termination** (HTTPS) for your websites. - **Stickiness** with cookies, when an app needs it. - **High availability across AZs.** - **Separate public from private traffic:** the load balancer is public, the instances can stay private. ## Why a managed (Elastic) load balancer [#why-a-managed-elastic-load-balancer] - AWS **guarantees it works**, and handles upgrades, maintenance and its own high availability. It scales itself as traffic grows. - AWS gives you only a few configuration knobs. - Running your own (for example NGINX or HAProxy on EC2) can cost less, but it's much more work. - It's **integrated** with many services: EC2, Auto Scaling groups, ECS, AWS Certificate Manager (ACM), CloudWatch, Route 53, AWS WAF and Global Accelerator. ## How it works [#how-it-works] - A **listener** checks for connections on a protocol and port, for example HTTPS on 443. - The listener's **rules** send each request to a **target group**: a set of targets (instances, IP addresses, Lambda functions or containers) with the protocol and port to use. - The load balancer runs a **node in each AZ** you enable, and DNS spreads clients across the nodes. (An Application Load Balancer needs at least two AZs.) - A load balancer is **internet-facing** (public DNS name and IPs) or **internal** (private IPs, reachable only inside the VPC or connected networks). ### Health checks [#health-checks] Health checks let the load balancer know whether a target can answer requests. - Set per target group: a **protocol, port and path**, for example `HTTP`, port `80`, path `/health`. - A target is **healthy** if it answers with a success code (200 by default for HTTP) for a number of checks in a row, and **unhealthy** after several failures. - Unhealthy targets get no traffic until they pass again. An Auto Scaling group can also use these results to **replace** them. ## The four types [#the-four-types]
![Application LB at layer 7, Network LB at layer 4, Gateway LB at layer 3, and the old Classic LB](/diagrams/scaling-lb-types.light.svg) ![Application LB at layer 7, Network LB at layer 4, Gateway LB at layer 3, and the old Classic LB](/diagrams/scaling-lb-types.dark.svg)
Pick by the layer and protocol you need.
- **[Application Load Balancer](/docs/scaling/alb)** (ALB, 2016): layer 7, HTTP, HTTPS, WebSocket and gRPC. Routes by URL path, hostname, headers and more. - **[Network Load Balancer](/docs/scaling/nlb)** (NLB, 2017): layer 4, TCP, UDP, TLS and QUIC. Millions of requests per second, static IPs. - **[Gateway Load Balancer](/docs/scaling/gwlb)** (GWLB, 2020): layer 3, IP packets. Sends traffic through firewalls and other appliances. - **Classic Load Balancer** (CLB, 2009): the old generation, layers 4 and 7 (HTTP, HTTPS, TCP, SSL). One fixed hostname per CLB, one certificate. Use the newer types: they have more features. AWS now recommends **migrating** Classic Load Balancers to an ALB or NLB. ## Security groups [#security-groups]
![The load balancer security group allows 443 from anywhere; the instance security group allows 80 only from the load balancer security group](/diagrams/scaling-lb-sg.light.svg) ![The load balancer security group allows 443 from anywhere; the instance security group allows 80 only from the load balancer security group](/diagrams/scaling-lb-sg.dark.svg)
Users reach the instances only through the load balancer.
1. The **load balancer's security group** allows HTTP and HTTPS (80, 443) from anywhere (`0.0.0.0/0`). 2. The **instances' security group** allows HTTP (80) **only from the load balancer's security group**, by [referencing it](/docs/compute/security-groups#referencing-other-security-groups). 3. Nobody can reach the instances directly, even if they guess an IP. ## Pricing [#pricing] - Each load balancer is billed **per hour** plus **capacity units** for the traffic it handles (LCUs for ALB, NLCUs for NLB, GLCUs for GWLB). An ALB in us-east-1 costs about **$0.0225 an hour** (about $16 a month) before capacity units. - An internet-facing load balancer also pays for its **public IPv4 addresses** ($0.005 an hour each, one per AZ). - Data transfer is extra, including cross-AZ traffic in some cases (see [cross-zone load balancing](/docs/scaling/sticky-sessions-cross-zone#cross-zone-load-balancing)). ## Exam tips [#exam-tips] - **"Single DNS name in front of many instances"**, **"distribute traffic"**, **"remove unhealthy instances"** → Elastic Load Balancing. - **"Instances must only accept traffic from the load balancer"** → instance security group references the load balancer's security group. - **"HTTP routing by path or host"** → ALB. **"TCP/UDP, extreme performance, static IP"** → NLB. **"Third-party firewall appliances"** → GWLB. - **"Classic Load Balancer"** in an answer is almost never right for a new design. ## Common traps [#common-traps] - **"A load balancer makes the app highly available on its own."** Only if targets run in at least two AZs. - **"Allow 0.0.0.0/0 on the instances too."** Then the load balancer can be bypassed. - **"A health check failure terminates the instance."** The load balancer only stops sending traffic; an Auto Scaling group with ELB health checks replaces it. ## Hands-on lab: two web servers behind an ALB [#hands-on-lab-two-web-servers-behind-an-alb] **Goal:** put two instances behind an Application Load Balancer and watch it spread requests and skip a failed instance. Two `t3.micro` instances (about $0.02 an hour each with public IPs), plus the ALB at about $0.0225 an hour, two public IPv4 addresses ($0.01 an hour) and a tiny capacity-unit charge: under **$0.10 an hour** in total. Delete the ALB at the end: it bills by the hour even with no traffic. ### Launch two web servers [#launch-two-web-servers] Launch **two** `t3.micro` instances (`saa-web-1`, `saa-web-2`), Amazon Linux 2023, tag `Project=saa-lab`, in **two different subnets** (AZs), with security group `saa-web-sg` from the [EC2 basics lab](/docs/compute/ec2-basics#hands-on-lab-launch-a-web-server-with-user-data) and the same web server user data. Each page shows its own hostname. ### Create a target group [#create-a-target-group] **EC2 → Target groups → Create target group**: type **Instances**, name `saa-tg`, protocol HTTP, port 80, health check path `/`. Register both instances on port 80 and create. ### Create the load balancer [#create-the-load-balancer] **Load balancers → Create → Application Load Balancer**: name `saa-alb`, **internet-facing**, IPv4, the default VPC, **at least two AZs** (the ones your instances are in). Create a new security group `saa-alb-sg` allowing **HTTP 80 from anywhere**. Listener HTTP:80 → forward to `saa-tg`. Tag `Project=saa-lab`, create. ### Test it [#test-it] When the state is *Active* and both targets are *healthy* (Target groups → Targets), open the ALB's **DNS name** in your browser and refresh several times. The hostname alternates between the two instances. ### Fail an instance [#fail-an-instance] Stop `saa-web-1`. In a minute its target shows *unhealthy* (then unused), and every refresh shows `saa-web-2`. Start it again and it rejoins. ### Lock the instances down (optional) [#lock-the-instances-down-optional] Edit `saa-web-sg`: replace the HTTP rule's source `0.0.0.0/0` with the security group `saa-alb-sg`. The site still works through the ALB, but the instances' own public IPs no longer answer on port 80. **Expected result:** one DNS name serving both instances in turn, and traffic moving away from a failed instance automatically. **Clean up:** keep everything if you're going straight on to the [ALB lab](/docs/scaling/alb#hands-on-lab-route-by-query-string-and-return-a-fixed-response). Otherwise delete the load balancer `saa-alb`, then the target group `saa-tg`, terminate both instances, and delete `saa-alb-sg`. ## AWS documentation [#aws-documentation] - [What is Elastic Load Balancing?](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) - [How Elastic Load Balancing works](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/how-elastic-load-balancing-works.html) - [Health checks for Application Load Balancer target groups](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html) - [What is a Classic Load Balancer?](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/introduction.html) - [Elastic Load Balancing pricing](https://aws.amazon.com/elasticloadbalancing/pricing/) # Gateway Load Balancer (/docs/scaling/gwlb) ## What it is [#what-it-is] Many companies must inspect all their network traffic with **third-party appliances**: firewalls, intrusion detection and prevention systems (IDS/IPS), deep packet inspection, payload manipulation. Running a fleet of these appliances, scaling it and keeping traffic flowing through it is hard. The **[Gateway Load Balancer](/docs/glossary#term-gateway-load-balancer)** (GWLB) makes it easy to **deploy, scale and manage** such virtual appliances in AWS. It works at **layer 3** (IP packets, all ports) and combines two jobs: - a **transparent network gateway**: a single entry and exit point for all traffic; - a **load balancer** that spreads that traffic across your appliances and scales with demand. ## How it works [#how-it-works]
![A route table sends user traffic to the Gateway Load Balancer, which passes it over GENEVE port 6081 to a target group of appliances; inspected traffic returns and goes on to the application](/diagrams/scaling-gwlb.light.svg) ![A route table sends user traffic to the Gateway Load Balancer, which passes it over GENEVE port 6081 to a target group of appliances; inspected traffic returns and goes on to the application](/diagrams/scaling-gwlb.dark.svg)
Traffic takes a detour through the appliances.
1. You change **route tables** so traffic between users and the application goes to the GWLB (through a **Gateway Load Balancer endpoint** in the VPC). 2. The GWLB forwards the packets to an appliance in its **target group**, wrapped in the **GENEVE protocol on port 6081**. 3. The appliance **inspects** the traffic and either drops it or sends it back to the GWLB. 4. Allowed traffic continues to the **application**. Neither side notices the detour. The GWLB keeps each flow on the same appliance (flow stickiness), so stateful firewalls see both directions of a connection. ### Target groups [#target-groups] - **EC2 instances**; - **IP addresses**, which must be private IPs. ## Exam tips [#exam-tips] - **"Third-party firewall / IDS / IPS / deep packet inspection appliances"**, **"inspect all traffic"** → Gateway Load Balancer. - **"GENEVE protocol on port 6081"** → GWLB. - **"Layer 3"** load balancer → GWLB (ALB is layer 7, NLB layer 4). ## Common traps [#common-traps] - **"Use an NLB to send traffic through firewall appliances."** For transparent inspection of all traffic, GWLB is the purpose-built answer. - **"GWLB routes HTTP requests by path."** It works on IP packets; it doesn't read HTTP. ## Check yourself [#check-yourself] A GWLB lab needs licensed appliance software from the AWS Marketplace and a second VPC, so instead: A Gateway Load Balancer with the firewall instances in its target group, and Gateway Load Balancer endpoints plus route table changes in each VPC. GENEVE on port 6081. ## AWS documentation [#aws-documentation] - [What is a Gateway Load Balancer?](https://docs.aws.amazon.com/elasticloadbalancing/latest/gateway/introduction.html) - [Getting started with Gateway Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/gateway/getting-started.html) # Load Balancing & Auto Scaling (/docs/scaling) ## What it is [#what-it-is] An app that runs on one server has two problems: when traffic grows, the server gets slow, and when the server fails, the app is down. This group covers the two services that fix both: - **[Elastic Load Balancing](/docs/glossary#term-elastic-load-balancing)** spreads requests over many servers and stops sending traffic to failed ones. - **[Amazon EC2 Auto Scaling](/docs/glossary#term-auto-scaling-group)** adds and removes servers as the load changes, and replaces failed ones. Used together, across several Availability Zones, they're the standard design for almost every web application on AWS. ## Scalability and high availability [#scalability-and-high-availability]
![Vertical scaling moves to a bigger instance, horizontal scaling adds instances, high availability spreads them across AZs](/diagrams/scaling-three-ideas.light.svg) ![Vertical scaling moves to a bigger instance, horizontal scaling adds instances, high availability spreads them across AZs](/diagrams/scaling-three-ideas.dark.svg)
Three ideas that are often confused.
**[Scalability](/docs/glossary#term-scalability)** means a system can handle a bigger load by adapting. There are two kinds. The course explains them with a call centre: ### Vertical scalability (scale up and down) [#vertical-scalability-scale-up-and-down] Make the instance **bigger**, like replacing a junior phone operator with a senior one who handles more calls. - Example: move an app from a `t3.micro` to a `t3.large`. On EC2 the range runs from `t3.nano` (0.5 GiB of memory) to high-memory U instances with up to 32 TiB. - Common for systems that aren't distributed, such as a **database**. RDS and ElastiCache scale vertically. - There's always a **hardware limit**, and changing size usually means a restart. ### Horizontal scalability (scale out and in) [#horizontal-scalability-scale-out-and-in] Add **more** instances, like hiring more operators. This is also called **[elasticity](/docs/glossary#term-elasticity)** when it happens automatically with demand. - Needs a **distributed** system: the app must work when requests land on any instance. - Normal for modern web applications, and easy on AWS with **Auto Scaling groups** and **load balancers**. ### High availability [#high-availability] **[High availability](/docs/glossary#term-high-availability)** means running the app in **at least two data centres** (Availability Zones), so it survives losing one, like having call centres in two cities. - **Active:** instances in every AZ serve traffic at once (horizontal scaling across AZs). - **Passive:** a standby waits in another AZ and takes over on failure (for example RDS Multi-AZ). - For EC2: an **Auto Scaling group** and a **load balancer**, both set to use several AZs. Scalability is about **load**; high availability is about **failure**. They usually go together, but one doesn't guarantee the other: ten instances in one AZ scale well but go down with the AZ. ## In this group [#in-this-group] ### Load balancing [#load-balancing] ### Auto Scaling [#auto-scaling] ## Exam tips [#exam-tips] - **"Handle more load by adding instances"**, **"elastic"** → horizontal scaling with an Auto Scaling group. - **"Survive the failure of an AZ / data centre"** → instances in at least two AZs behind a load balancer. - **"Database needs more power"** → usually vertical scaling (a bigger instance class), or read replicas. - **"Highly available and scalable web tier"** → ALB + Auto Scaling group across multiple AZs. ## AWS documentation [#aws-documentation] - [What is Elastic Load Balancing?](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) - [What is Amazon EC2 Auto Scaling?](https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html) - [Reliability pillar: design for horizontal scaling](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/welcome.html) # Network Load Balancer (/docs/scaling/nlb) ## What it is [#what-it-is] The **[Network Load Balancer](/docs/glossary#term-network-load-balancer)** (NLB) works at **layer 4**: it forwards **TCP and UDP** connections without looking inside the HTTP requests. - Handles **millions of requests per second** with **ultra-low latency**, and absorbs sudden spikes. - Listeners for **TCP, TLS (secure TCP), UDP, TCP_UDP**, and now **QUIC**. - **One static IP address per AZ**, and you can assign your own **Elastic IPs** to an internet-facing NLB. That's helpful when clients must allow-list specific IPs. - Used for **extreme performance**, **non-HTTP protocols** (gaming, IoT, VoIP, databases), and anything needing **static IPs**. ## Target groups [#target-groups]
![Clients send TCP or UDP traffic to an NLB with a static IP per AZ, which forwards to EC2 instances, private IP addresses, or an Application Load Balancer](/diagrams/scaling-nlb-targets.light.svg) ![Clients send TCP or UDP traffic to an NLB with a static IP per AZ, which forwards to EC2 instances, private IP addresses, or an Application Load Balancer](/diagrams/scaling-nlb-targets.dark.svg)
Three kinds of NLB target.
An NLB target group contains one kind of target: - **EC2 instances**; - **IP addresses**, which must be private IPs (instances, containers or on-premises servers); - **an Application Load Balancer**: the NLB gives the static IPs, the ALB does the HTTP routing behind it. **Health checks** can use **TCP, HTTP or HTTPS**, even when the traffic itself is TCP or UDP. ### How traffic flows [#how-traffic-flows] - An NLB keeps each TCP connection (or UDP flow) on **one target** for its whole life, choosing by a hash of the source and destination addresses and ports. - For instance targets, the target sees the **client's real IP** (client IP preservation), unlike with an ALB. - With a **TCP listener on port 443**, traffic passes through still encrypted, so your targets decrypt it. With a **TLS listener**, the NLB terminates TLS itself. - NLBs now support **security groups**, so instance security groups can reference the NLB's group, as with an ALB. NLBs gained **security groups** in 2023 (before, you had to allow client IPs on the targets), and they now support **QUIC** listeners for HTTP/3-style traffic. Cross-zone load balancing is still off by default for NLBs. ## ALB or NLB? [#alb-or-nlb] - **HTTP-aware routing, redirects, authentication, Lambda targets** → ALB. - **TCP or UDP, extreme performance, static or Elastic IPs, client IP preserved** → NLB. - **Both static IPs and HTTP routing** → NLB in front of an ALB. ## Exam tips [#exam-tips] - **"TCP / UDP traffic"**, **"millions of requests per second"**, **"ultra-low latency"** → NLB. - **"Static IP address" or "Elastic IP" for a load balancer**, **"clients allow-list our IPs"** → NLB. - **"Static IPs and path-based routing"** → NLB with an ALB as the target (or Global Accelerator in front of an ALB). - **"End-to-end encryption, targets must decrypt"** → NLB with a TCP listener on 443 (passthrough). - **"Gaming, VoIP, IoT over UDP"** → NLB. ## Common traps [#common-traps] - **"Route by URL path on an NLB."** NLBs don't read HTTP; use an ALB. - **"NLB targets can be Lambda functions."** Lambda targets are for ALBs. - **"Target IPs can be public."** IP targets must be private. ## Check yourself [#check-yourself] An NLB lab works like the [ALB lab](/docs/scaling/elb-overview#hands-on-lab-two-web-servers-behind-an-alb) with the same cost, so instead of repeating it: A Network Load Balancer with a UDP listener on 7777 and Elastic IPs assigned in each AZ. An internet-facing NLB with Elastic IPs, whose target group is an Application Load Balancer that routes by path. (Global Accelerator in front of the ALB also works.) An NLB with a TCP listener on port 443, so TLS passes through and the instances terminate it. (An ALB re-encrypting to HTTPS targets also keeps traffic encrypted, but the ALB decrypts it in between.) ## AWS documentation [#aws-documentation] - [What is a Network Load Balancer?](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html) - [Target groups for your Network Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html) - [Listeners for your Network Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-listeners.html) - [Security groups for your Network Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-security-groups.html) # Scaling policies (/docs/scaling/scaling-policies) ## What it is [#what-it-is] A **scaling policy** tells an Auto Scaling group when to change its desired capacity. Most policies watch a **CloudWatch metric** and react to it; others follow a schedule or a forecast. ## Scaling on CloudWatch alarms [#scaling-on-cloudwatch-alarms]
![A CloudWatch metric feeds an alarm, which triggers a scaling policy, and the Auto Scaling group launches and registers instances](/diagrams/scaling-alarm-flow.light.svg) ![A CloudWatch metric feeds an alarm, which triggers a scaling policy, and the Auto Scaling group launches and registers instances](/diagrams/scaling-alarm-flow.dark.svg)
Metric, alarm, policy, action.
1. A **CloudWatch metric**, such as the **average CPU across the group's instances** or a custom metric, is collected. 2. A **CloudWatch alarm** goes off when the metric crosses a threshold, for example CPU above 70% for 5 minutes. 3. The alarm triggers a **scaling policy**: scale out (add instances) or scale in (remove them). 4. The group launches or terminates instances, and registers them with the load balancer. ## The policy types [#the-policy-types]
![Target tracking keeps CPU at 40 percent; step or simple adds 2 when CPU is over 70 percent; scheduled sets min 10 on Friday at 17:00; predictive forecasts from history](/diagrams/scaling-policies.light.svg) ![Target tracking keeps CPU at 40 percent; step or simple adds 2 when CPU is over 70 percent; scheduled sets min 10 on Friday at 17:00; predictive forecasts from history](/diagrams/scaling-policies.dark.svg)
Four ways to decide how many instances to run.
### Dynamic scaling [#dynamic-scaling] - **[Target tracking](/docs/glossary#term-target-tracking-scaling)** (recommended): you pick a metric and a target value, for example "keep the group's average CPU around 40%". Auto Scaling creates and manages the alarms, scaling out and in to stay near the target. The simplest to set up. - **Step scaling:** you create the CloudWatch alarms and say how much to change at each level, for example "CPU above 70%: add 2 instances; above 90%: add 4; below 30%: remove 1". - **Simple scaling:** one alarm, one change, then wait for the cooldown. Older; AWS recommends target tracking or step scaling instead. ### Scheduled scaling [#scheduled-scaling] Change capacity at **known times**, based on usage patterns you already know. For example: "set the minimum to 10 at 17:00 every Friday" before the weekend rush, and back to 2 on Monday. ### Predictive scaling [#predictive-scaling] Auto Scaling **analyses the history** of your load, finds **daily and weekly patterns**, **forecasts** the coming load and **schedules** capacity ahead of it. It's best for regular, cyclical traffic and apps that take a while to start, because instances are ready before the peak arrives. It works alongside dynamic scaling. ## Good metrics to scale on [#good-metrics-to-scale-on] - **CPUUtilization:** average CPU across the instances. The common default. - **RequestCountPerTarget** (`ALBRequestCountPerTarget`): requests per instance from the ALB, for example "keep about 1,000 requests per target". Good for web apps, because it tracks real demand. - **Average NetworkIn / NetworkOut:** for apps limited by network. - **Any custom metric** you publish to CloudWatch, such as queue length (see [SQS with Auto Scaling](/docs/integration/sqs#scaling-consumers-with-an-auto-scaling-group)) or active sessions. ## Cooldowns and warmup [#cooldowns-and-warmup] - After a scaling activity, a group using **simple scaling** waits for a **cooldown** (**300 seconds** by default) before scaling again, so metrics can settle and it doesn't overreact. - Target tracking and step policies instead use an **instance warmup**: new instances don't count toward the metric until they've had time to start. AWS recommends setting a **default instance warmup** for the group. - **Tip:** use a ready-to-go (**golden**) **AMI**, so instances start serving sooner and cooldowns or warmups can be shorter. ## Warm pools [#warm-pools]
![A warm pool keeps set-up, stopped instances next to the Auto Scaling group; on scale-out they start and join the group in service](/diagrams/scaling-warm-pool.light.svg) ![A warm pool keeps set-up, stopped instances next to the Auto Scaling group; on scale-out they start and join the group in service](/diagrams/scaling-warm-pool.dark.svg)
Instances that are already set up, waiting to start.
Some apps take a long time to boot, for example because they load gigabytes of data first. A **[warm pool](/docs/glossary#term-warm-pool)** keeps **pre-initialised instances** next to the group. - Instances in the pool can be kept **stopped** (you pay only for EBS), **hibernated** (memory kept), or **running**. - On scale-out the group takes instances from the pool, which start serving **much faster** than brand-new ones. - By default the pool size is the group's maximum minus its desired capacity. - Don't add one if boot time isn't a problem: it costs money for nothing. ## Instance refresh [#instance-refresh] An **[instance refresh](/docs/glossary#term-instance-refresh)** replaces the instances in a group in a **rolling** way, for example after you create a **new launch template version** with a new AMI or instance type. - Instances are replaced in batches while a **minimum healthy percentage** (90% by default) keeps serving traffic. - You can add **checkpoints** to pause and check, **skip** instances that already match, and **roll back** automatically if the new version is unhealthy. - This gives **immutable** deployments: instead of patching servers in place, you replace them with new ones built from the new image. Warm pools and instance refresh are in the exam guide but not in the course slides. These sections are written from the AWS documentation. ## AWS Auto Scaling and Application Auto Scaling [#aws-auto-scaling-and-application-auto-scaling]
![Three services with auto scaling in the name: AWS Auto Scaling offers scaling plans in one place and works through EC2 Auto Scaling, which scales EC2 instances in Auto Scaling groups, and Application Auto Scaling, which scales other services such as ECS services, DynamoDB tables, Aurora replicas, Lambda, ElastiCache and Spot Fleet](/diagrams/scaling-auto-scaling-services.light.svg) ![Three services with auto scaling in the name: AWS Auto Scaling offers scaling plans in one place and works through EC2 Auto Scaling, which scales EC2 instances in Auto Scaling groups, and Application Auto Scaling, which scales other services such as ECS services, DynamoDB tables, Aurora replicas, Lambda, ElastiCache and Spot Fleet](/diagrams/scaling-auto-scaling-services.dark.svg)
Three services with "Auto Scaling" in the name.
Three AWS services have "Auto Scaling" in their name, and the exam guide lists two of them by name. They fit together like this: - **Amazon EC2 Auto Scaling** is everything on this page and the [Auto Scaling groups](/docs/scaling/auto-scaling-groups) page: it adds and removes **EC2 instances** in Auto Scaling groups. - **Application Auto Scaling** scales **other AWS services** with the same kinds of policy (target tracking, step and scheduled scaling): the task count of **ECS services**, the read and write capacity of **DynamoDB** tables, the number of **Aurora replicas**, **Lambda** provisioned concurrency, **ElastiCache** clusters, **Spot Fleets** and more. You usually set it up from each service's own console, for example "Aurora replica auto scaling" in the RDS console. - **[AWS Auto Scaling](/docs/glossary#term-aws-auto-scaling)** is a single console for **scaling plans**. A scaling plan sets up scaling for **several related resources at once**: EC2 Auto Scaling groups, ECS services, DynamoDB tables and indexes, Aurora replicas and Spot Fleets. - It **discovers** the scalable resources of your application, found by **tags** or by **CloudFormation stack**. - It offers **scaling strategies** with recommendations: optimize for **availability**, for **cost**, or a balance of both. - It sets up **dynamic scaling** (target tracking) through EC2 Auto Scaling and Application Auto Scaling, and can add **predictive scaling** for Auto Scaling groups. For example, a web app tagged `app=shop` has an Auto Scaling group, an ECS service and a DynamoDB table. One scaling plan keeps the instances near 50% CPU, the ECS tasks near 60% CPU and the table near 70% capacity use, instead of three separate setups. The course slides don't cover AWS Auto Scaling as a separate service, but it is on the exam guide's in-scope list. This section is written from the AWS documentation. ## Other features worth knowing [#other-features-worth-knowing] - **Lifecycle hooks** pause an instance while it launches (`Pending:Wait`) or terminates (`Terminating:Wait`), one hour by default, so a script can install software or copy logs first. - **Termination policy:** on scale-in, the group first keeps the AZs balanced, then by default removes instances with the oldest launch template or configuration. - **Capacity rebalancing** replaces Spot Instances that get a rebalance recommendation before they're interrupted. ## Exam tips [#exam-tips] - **"Keep average CPU at 50%"**, **"simplest way to scale on a metric"** → target tracking. - **"Scale every Friday at 5 pm"**, **"known event"** → scheduled scaling. - **"Daily or weekly cyclical traffic, scale ahead of demand"** → predictive scaling. - **"Scale by number of requests per instance"** → target tracking on `ALBRequestCountPerTarget`. - **"Instances take a long time to boot, so scale-out is too slow"** → warm pool (and a golden AMI). - **"Roll out a new AMI to all instances in the group with no downtime"** → new launch template version + instance refresh. - **"Run a script before an instance is terminated"** → lifecycle hook. - **"Group scales out again too soon"** → cooldown (simple scaling) or instance warmup. - **"Set up scaling for EC2, ECS, DynamoDB and Aurora of one application from a single place"**, **"scaling plan"** → AWS Auto Scaling. - **"Scale DynamoDB capacity, ECS tasks or Aurora replicas automatically"** → Application Auto Scaling (through each service's auto scaling settings). ## Common traps [#common-traps] - **"Scale on the CPU of one instance."** Use the group-wide average (or a per-target metric). - **"Use simple scaling for new designs."** Target tracking or step scaling is recommended. - **"Instance refresh changes the launch template."** You change the template first; the refresh replaces the instances. - **"AWS Auto Scaling and EC2 Auto Scaling are the same service."** EC2 Auto Scaling scales instances; AWS Auto Scaling creates scaling plans across several services. ## Hands-on lab: scale on CPU with target tracking [#hands-on-lab-scale-on-cpu-with-target-tracking] **Goal:** add a target tracking policy and watch the group scale out when you load the CPU, then back in. Uses `saa-asg` from the [Auto Scaling groups lab](/docs/scaling/auto-scaling-groups#hands-on-lab-a-self-healing-group-behind-an-alb), plus up to two more `t3.micro` instances for a few minutes: well under $0.20 for the lab. Burstable instances running at 100% CPU may add a few cents of CPU credit charges. ### Add the policy [#add-the-policy] Open `saa-asg` → **Automatic scaling → Create dynamic scaling policy**: type **Target tracking scaling**, metric **Average CPU utilization**, target value **40**, instance warmup 60 seconds. Create. ### Load the CPU [#load-the-cpu] Connect to one of the group's instances with EC2 Instance Connect and run a busy loop on both vCPUs: ```bash yes > /dev/null & yes > /dev/null & ``` ### Watch it scale out [#watch-it-scale-out] In a few minutes, CloudWatch sees the group's average CPU above 40%. The **Activity** tab shows new instances launching, and the desired capacity rises (up to the maximum of 4). In **CloudWatch → Alarms** you can see the two alarms target tracking created for you. ### Stop the load [#stop-the-load] Run `pkill yes` on the instance. Over the next 15 minutes or so, the group scales back in to the minimum of 2 (scale-in is deliberately slower than scale-out). **Expected result:** the group adds instances under load and removes them when the load is gone, without you touching the desired capacity. **Clean up:** delete the Auto Scaling group `saa-asg` (it terminates its instances), then the load balancer, the target group `saa-asg-tg`, and the launch template `saa-lt`. Target tracking deletes its own alarms with the policy. ## AWS documentation [#aws-documentation] - [Dynamic scaling for Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scale-based-on-demand.html) - [Target tracking scaling policies](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-target-tracking.html) - [Scheduled scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html) - [Predictive scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-predictive-scaling.html) - [Warm pools](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-warm-pools.html) - [Instance refresh](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-instance-refresh.html) - [Lifecycle hooks](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html) - [What is a scaling plan? (AWS Auto Scaling)](https://docs.aws.amazon.com/autoscaling/plans/userguide/what-is-a-scaling-plan.html) - [What is Application Auto Scaling?](https://docs.aws.amazon.com/autoscaling/application/userguide/what-is-application-auto-scaling.html) # SSL/TLS, SNI and deregistration delay (/docs/scaling/ssl-tls-sni) ## SSL/TLS basics [#ssltls-basics] An **SSL/TLS certificate** lets traffic between clients and your load balancer be **encrypted in transit** (in-flight encryption). - **SSL** (Secure Sockets Layer) is the old name. **TLS** (Transport Layer Security) is the newer version that's actually used today, but people still say "SSL certificate". - **Public certificates** are issued by **certificate authorities** (CAs) such as DigiCert, GlobalSign, Let's Encrypt, or Amazon (through ACM). - Certificates **expire** and must be renewed. ## Certificates on a load balancer [#certificates-on-a-load-balancer] A common setup: users connect with **HTTPS** (encrypted) over the internet to the load balancer, which decrypts and sends **HTTP** to the instances over the private VPC network. That's *SSL termination* at the load balancer: the instances don't spend CPU on encryption. If rules require it, the load balancer can re-encrypt to HTTPS targets instead. - The load balancer uses an **X.509 certificate** (an SSL/TLS server certificate). - Manage certificates with **[AWS Certificate Manager](/docs/glossary#term-aws-certificate-manager)** (ACM): free public certificates that **renew automatically**. You can also upload your own. - An **HTTPS listener** needs a **default certificate**, and can have a **list** of extra certificates for more domains. - A **security policy** chooses which TLS versions and ciphers clients may use, for example allowing older versions for legacy clients, or only TLS 1.2 and 1.3. ## Server Name Indication (SNI) [#server-name-indication-sni]
![The client asks for www.mycorp.com; the HTTPS listener picks the matching certificate from its list and routes to the www.mycorp.com target group](/diagrams/scaling-sni.light.svg) ![The client asks for www.mycorp.com; the HTTPS listener picks the matching certificate from its list and routes to the www.mycorp.com target group](/diagrams/scaling-sni.dark.svg)
Many websites, many certificates, one listener.
**[SNI](/docs/glossary#term-sni)** solves the problem of loading **multiple certificates onto one server** that hosts several websites. 1. In the first step of the TLS handshake, the **client says which hostname** it wants, for example `www.mycorp.com`. 2. The load balancer **picks the matching certificate** from its list (or uses the default one if none matches). 3. A listener rule on the host header sends the request to the right **target group**. SNI works with **ALB, NLB** (TLS listeners) and **CloudFront**. It does **not** work with the Classic Load Balancer. ### Certificates per load balancer type [#certificates-per-load-balancer-type] - **Classic Load Balancer:** only **one** certificate. For several hostnames with different certificates you need several CLBs. - **Application Load Balancer:** many listeners with many certificates, using SNI. - **Network Load Balancer:** many TLS listeners with many certificates, using SNI. ## Deregistration delay (connection draining) [#deregistration-delay-connection-draining]
![The load balancer lets a deregistering instance finish in-flight requests for up to 300 seconds by default while new connections go to the other instances](/diagrams/scaling-draining.light.svg) ![The load balancer lets a deregistering instance finish in-flight requests for up to 300 seconds by default while new connections go to the other instances](/diagrams/scaling-draining.dark.svg)
Let old requests finish before removing an instance.
When an instance is being **deregistered** (scale-in, deployment) or becomes unhealthy, cutting it off at once would break requests still in progress. - The feature is called **Connection Draining** on a CLB and **Deregistration Delay** on ALB and NLB. - The load balancer **stops sending new requests** to that instance, but gives **in-flight requests** time to complete. - From **1 to 3,600 seconds**, **300 seconds** by default; **0** turns it off. - Set it **low** (for example 30 seconds) if your requests are short, so deployments and scale-in don't wait five minutes for nothing. ## Exam tips [#exam-tips] - **"HTTPS for the website, free certificate that renews itself"** → ACM certificate on the load balancer's HTTPS listener. - **"Host several HTTPS domains on one load balancer"** → ALB or NLB with multiple certificates and **SNI**. - **"Classic Load Balancer with several domains"** → needs one CLB per certificate (or migrate to ALB). - **"Support old clients' TLS versions"** → choose a security policy that allows them. - **"In-flight requests fail during scale-in or deployments"** → increase the deregistration delay. **"Deployments take 5 minutes per instance for short requests"** → lower it. ## Common traps [#common-traps] - **"SNI works on every load balancer."** Not on the Classic Load Balancer. - **"Remember to renew the load balancer's ACM certificate every year."** ACM renews its certificates automatically while they're in use (with DNS validation); uploaded third-party certificates are the ones you must renew yourself. ## Check yourself [#check-yourself] An HTTPS lab needs a domain name you own (to validate an ACM certificate), so instead: An Application Load Balancer with an HTTPS listener holding both ACM certificates; SNI picks the right one per request, and host-header rules route to each target group. Raise the target group's deregistration delay to at least 600 seconds, so uploads in progress can finish before the instance is removed. ## AWS documentation [#aws-documentation] - [Create an HTTPS listener for your Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html) - [Security policies for your Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/describe-ssl-policies.html) - [Edit target group attributes (deregistration delay)](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/edit-target-group-attributes.html) - [What is AWS Certificate Manager?](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) # Sticky sessions and cross-zone load balancing (/docs/scaling/sticky-sessions-cross-zone) ## Sticky sessions (session affinity) [#sticky-sessions-session-affinity] Normally a load balancer may send each request from a user to a different target. **[Sticky sessions](/docs/glossary#term-sticky-sessions)** make the same client always reach the **same target**, for a period you choose.
![The ALB reads each client's cookie, so clients 1 and 2 always reach instance A and client 3 always reaches instance B](/diagrams/scaling-sticky.light.svg) ![The ALB reads each client's cookie, so clients 1 and 2 always reach instance A and client 3 always reaches instance B](/diagrams/scaling-sticky.dark.svg)
Each client keeps going to the same instance.
- Works with **Application, Network and Classic Load Balancers**. ALB and CLB use a **cookie** with an expiry you control; NLB sticks by the client's **source IP**. - **Use case:** an app that keeps session data (a shopping cart, a login) in the server's memory, so the user doesn't lose it. - **Downside:** load can become **uneven**: a few heavy users may pin themselves to one instance, and scaling in can still cut sessions. Storing sessions outside the servers (ElastiCache, DynamoDB) is usually better, and lets you turn stickiness off. ### Cookie types (ALB) [#cookie-types-alb] - **Duration-based cookie:** generated by the load balancer, named **`AWSALB`** (**`AWSELB`** on a CLB). You set how long it lasts, from 1 second to 7 days. - **Application-based cookie:** - a **custom cookie** generated by your application (the target). It can carry any attributes the app needs. You give its name per target group, and you mustn't use the reserved names `AWSALB`, `AWSALBAPP` or `AWSALBTG`; - plus an **application cookie** generated by the load balancer, named **`AWSALBAPP`**, which tracks the stickiness for your custom cookie. ## Cross-zone load balancing [#cross-zone-load-balancing] A load balancer has a **node in each AZ**, and DNS sends roughly the same share of clients to each node. The question is whether a node may send traffic to targets in **other** AZs.
![With 2 instances in AZ 1 and 8 in AZ 2, each node gets 50 percent; with cross-zone on, each instance gets 10 percent; with it off, AZ 1 instances get 25 percent and AZ 2 instances 6.25 percent](/diagrams/scaling-cross-zone.light.svg) ![With 2 instances in AZ 1 and 8 in AZ 2, each node gets 50 percent; with cross-zone on, each instance gets 10 percent; with it off, AZ 1 instances get 25 percent and AZ 2 instances 6.25 percent](/diagrams/scaling-cross-zone.dark.svg)
Same load balancer, same 10 instances, two results.
In this example AZ 1 has 2 instances and AZ 2 has 8. Each load balancer node gets 50% of the traffic. - **With cross-zone load balancing**, each node spreads its share across **all 10 instances**, so each gets **10%**. The load is even. - **Without it**, each node uses only **its own AZ**. The 2 instances in AZ 1 share 50%, **25% each**, while the 8 in AZ 2 get **6.25% each**. The AZ 1 instances work four times harder. ### Defaults per type [#defaults-per-type] - **Application Load Balancer:** always on at the load balancer; you can turn it off per **target group**. **No charge** for data between AZs. - **Network and Gateway Load Balancers:** **off** by default. You can turn it on, but you **pay** for data sent between AZs. - **Classic Load Balancer:** off by default when created with the API or CLI (on when created in the console); no charge between AZs. Keeping the same number of instances in every AZ (which Auto Scaling groups try to do) avoids the imbalance even without cross-zone. ## Exam tips [#exam-tips] - **"Users must keep their session on the same instance"** → sticky sessions (ALB cookie, or source IP on an NLB). - **"Load is uneven since enabling stickiness"** → that's the expected side effect; store sessions in ElastiCache or DynamoDB instead. - **"Uneven instance counts across AZs cause overloaded instances"** → turn on cross-zone load balancing. - **"Cross-zone on an NLB costs money"**; on an ALB it's free and on by default. ## Common traps [#common-traps] - **"Sticky sessions improve load distribution."** They make it worse; they trade balance for session continuity. - **"Cross-zone load balancing is off by default on ALB."** It's on for ALB, off for NLB and GWLB. ## Hands-on lab: turn on stickiness [#hands-on-lab-turn-on-stickiness] **Goal:** see an ALB send every request from your browser to one instance once stickiness is on. Uses the ALB and two instances from the [Elastic Load Balancing lab](/docs/scaling/elb-overview#hands-on-lab-two-web-servers-behind-an-alb) (rebuild them if you deleted them), under $0.10 an hour. ### Check the default [#check-the-default] Open the ALB's DNS name and refresh a few times: the hostname alternates. ### Turn on stickiness [#turn-on-stickiness] Open target group `saa-tg` → **Attributes → Edit** → turn on **Stickiness**, type **Load balancer generated cookie**, duration **1 minute**. Save. ### Test it [#test-it] Refresh many times: the hostname stays the same. In your browser's developer tools (**Application/Storage → Cookies**), you'll see the `AWSALB` cookie. Wait over a minute, or open a private window, and you may land on the other instance. ### See the cross-zone setting [#see-the-cross-zone-setting] Still in the target group's **Attributes**, note **Cross-zone load balancing: Inherit settings from load balancer**, which for an ALB means on. **Expected result:** with stickiness on, your browser keeps reaching the same instance thanks to the `AWSALB` cookie. **Clean up:** delete `saa-alb`, the target group, both instances and `saa-alb-sg`, unless you continue to the next lab. ## AWS documentation [#aws-documentation] - [Sticky sessions for your Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html) - [How Elastic Load Balancing works: cross-zone load balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/how-elastic-load-balancing-works.html) - [Configure cross-zone load balancing for a Classic Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-disable-crosszone-lb.html) # AWS Certificate Manager (ACM) (/docs/security/acm) ## What it is [#what-it-is]
![ACM with an Application Load Balancer: ACM issues and renews the TLS certificate on the load balancer; users connect over HTTPS, plain HTTP is redirected to HTTPS, and the load balancer forwards requests to the EC2 instances in its Auto Scaling group](/diagrams/sec-acm-alb.light.svg) ![ACM with an Application Load Balancer: ACM issues and renews the TLS certificate on the load balancer; users connect over HTTPS, plain HTTP is redirected to HTTPS, and the load balancer forwards requests to the EC2 instances in its Auto Scaling group](/diagrams/sec-acm-alb.dark.svg)
HTTPS on the load balancer, certificates managed for you.
**[AWS Certificate Manager](/docs/glossary#term-aws-certificate-manager)** (ACM) lets you easily provision, manage and deploy **TLS certificates**. - Provides **in-flight encryption** for websites (HTTPS). - Supports both **public** and **private** TLS certificates. - **Free** for public TLS certificates used with integrated services. - **Automatic** TLS certificate **renewal**. - **Integrations** (load TLS certificates on): - **Elastic Load Balancers** (CLB, ALB, NLB); - **CloudFront** distributions; - **APIs on API Gateway**. - On an ALB, add an **HTTP → HTTPS redirect** rule so every user ends up on HTTPS (see [SSL/TLS on load balancers](/docs/scaling/ssl-tls-sni)). ## Requesting public certificates [#requesting-public-certificates] 1. List the **domain names** to include in the certificate: - fully qualified domain name (FQDN): `corp.example.com`; - wildcard domain: `*.example.com`. 2. Select a **validation method**: - **DNS validation**, preferred for automation: ACM gives you a **CNAME record** to put in your DNS (one click with Route 53); - email validation: ACM sends emails to the contact addresses in the WHOIS database. 3. It can take a few hours to be verified. 4. The public certificate is enrolled for **automatic renewal**: ACM renews ACM-generated certificates **before they expire**. ACM public certificates are now valid for **198 days** (they used to be valid for 395). ACM renews DNS-validated certificates **45 days before expiry**; the slides' "60 days" applied to the older 395-day certificates. ACM is also **phasing out email validation during 2027**, so use DNS validation. The exam ideas don't change: ACM certificates are free and renew automatically, as long as they're DNS-validated and in use. ## Importing certificates [#importing-certificates]
![Watching imported certificates: ACM sends daily expiry events and the AWS Config rule acm-certificate-expiration-check flags certificates close to expiry; an EventBridge rule sends them to Lambda, SNS or SQS](/diagrams/sec-acm-expiry.light.svg) ![Watching imported certificates: ACM sends daily expiry events and the AWS Config rule acm-certificate-expiration-check flags certificates close to expiry; an EventBridge rule sends them to Lambda, SNS or SQS](/diagrams/sec-acm-expiry.dark.svg)
Imported certificates don't renew themselves.
- You can generate a certificate **outside ACM** and then **import** it. - **No automatic renewal**: you must import a new certificate before expiry. - **ACM sends daily expiration events** to EventBridge, starting 45 days before expiry for imported certificates (the number of days can be configured). - **AWS Config** has a managed rule, **`acm-certificate-expiration-check`**, to flag expiring certificates (configurable number of days). ## ACM with API Gateway [#acm-with-api-gateway] Create a **custom domain name** in API Gateway, then: - **Edge-optimized** (default, for global clients): requests are routed through CloudFront edge locations; the API Gateway still lives in one Region. **The TLS certificate must be in the same Region as CloudFront: `us-east-1`.** - **Regional** (clients in the same Region): **the TLS certificate must be imported in the same Region as the API stage.** - Then set up a **CNAME** or (better) an **alias** record in Route 53. See [API Gateway endpoint types](/docs/serverless/api-gateway#endpoint-types). ## Real-world examples [#real-world-examples] - **A start-up** requests `*.example.com` in ACM with DNS validation in Route 53 and attaches it to its ALB and CloudFront distribution; it never thinks about renewal again. - **A bank** must use certificates from its own provider. It imports them into ACM and uses an EventBridge rule on expiry events to open a ticket 30 days before. ## Exam tips [#exam-tips] - **"Free TLS certificates that renew automatically"** → ACM public certificates (DNS validation). - **"HTTPS on an ALB, CloudFront or API Gateway"** → ACM certificate. - **"Certificate for an edge-optimized API or CloudFront"** → ACM in **us-east-1**. - **"Imported certificate expiring"** → re-import before expiry; monitor with EventBridge expiry events or the Config rule. - **"TLS certificate on an EC2 instance directly"** → not a standard ACM public certificate (use your own, or the newer exportable certificates). ## Common traps [#common-traps] - **"ACM renews imported certificates."** Only certificates ACM issued. - **"Use an ACM certificate from eu-west-1 on CloudFront."** CloudFront needs the certificate in us-east-1. ## Check yourself [#check-yourself] Requesting a public certificate needs a domain you own, so instead: Request (or import) the certificate in ACM in us-east-1, create the custom domain name in API Gateway with that certificate, and point an alias record in Route 53 at it. Create an EventBridge rule on ACM's certificate approaching expiration events (or use the AWS Config rule acm-certificate-expiration-check) that notifies SNS; then import a renewed certificate. ## AWS documentation [#aws-documentation] - [What is AWS Certificate Manager?](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) - [ACM public certificate characteristics](https://docs.aws.amazon.com/acm/latest/userguide/acm-certificate-characteristics.html) - [Managed certificate renewal](https://docs.aws.amazon.com/acm/latest/userguide/managed-renewal.html) - [Import certificates into ACM](https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html) - [Amazon EventBridge support for ACM](https://docs.aws.amazon.com/acm/latest/userguide/supported-events.html) # AWS CloudHSM (/docs/security/cloudhsm) ## What it is [#what-it-is]
![AWS CloudHSM: a cluster of single-tenant HSMs spread across Availability Zones keeps keys synchronised; you manage the keys and users through the CloudHSM client, and AWS KMS can use the cluster as a custom key store](/diagrams/sec-cloudhsm.light.svg) ![AWS CloudHSM: a cluster of single-tenant HSMs spread across Availability Zones keeps keys synchronised; you manage the keys and users through the CloudHSM client, and AWS KMS can use the cluster as a custom key store](/diagrams/sec-cloudhsm.dark.svg)
Your own HSMs, run by AWS, keys managed by you.
- **KMS:** AWS manages the software for encryption. - **[CloudHSM](/docs/glossary#term-aws-cloudhsm):** AWS provisions encryption **hardware**. - **Dedicated hardware** (HSM = Hardware Security Module), **single-tenant**. - **You manage your own encryption keys entirely** (not AWS). - The HSM device is **tamper resistant**, **FIPS 140-2 or 140-3 Level 3** compliant. - Supports both **symmetric** and **asymmetric** encryption (SSL/TLS keys). - **No free tier.** - You must use the **CloudHSM client software**. - **Redshift** supports CloudHSM for database encryption and key management. - A good option to use with **SSE-C** encryption (you hold the keys S3 needs). **Who manages what:** - **AWS** manages the **hardware**. - **IAM permissions** only let you create, read, update and delete an **HSM cluster**. - The **CloudHSM software** manages the **keys** and the **users**. ## High availability [#high-availability] - CloudHSM clusters are **spread across multiple AZs** (HA). - Great for availability and durability: keys are synchronised between the HSMs of a cluster. ## Integration with AWS services [#integration-with-aws-services] - Through integration with **KMS**: configure a **KMS custom key store** backed by CloudHSM. - Services such as **EBS, S3 and RDS** then use KMS as usual, while the key material lives in your HSMs. - Key usage is still logged in **CloudTrail**. ## CloudHSM vs KMS [#cloudhsm-vs-kms] **AWS KMS:** - **Multi-tenant**, FIPS 140-3 Level 3. - Keys: AWS owned, AWS managed, customer managed. - Symmetric, asymmetric, digital signing. - Keys can be multi-Region (replicas); otherwise they stay in their Region. - Access with **IAM**; HA managed by AWS. - Audit with CloudTrail and CloudWatch. - Free tier. **AWS CloudHSM:** - **Single-tenant**, FIPS 140-2 or 140-3 Level 3. - Customer managed keys only. - Symmetric, asymmetric, digital signing and hashing. - Deployed and managed in a **VPC** (shareable across VPCs with peering). - **SSL/TLS acceleration**, **Oracle TDE** acceleration. - **You create users** and manage their permissions; HA by adding HSMs in several AZs. - Audit with CloudTrail, CloudWatch, and **MFA** support. - No free tier. ## Real-world examples [#real-world-examples] - **A payment processor** must keep keys on single-tenant, FIPS-validated hardware it controls. It uses a CloudHSM cluster in two AZs as a KMS custom key store, so S3 and EBS still use KMS. - **A web company** offloads TLS handshakes for its web servers to CloudHSM. ## Exam tips [#exam-tips] - **"Dedicated, single-tenant hardware", "you manage the keys", "FIPS 140 Level 3 HSM you control"** → CloudHSM. - **"Keys must never be accessible to AWS"** → CloudHSM. - **"SSE-C with keys in an HSM", "Oracle TDE", "SSL offload"** → CloudHSM. - **"Use CloudHSM keys with S3 or EBS encryption"** → KMS custom key store backed by CloudHSM. ## Common traps [#common-traps] - **"AWS can recover your CloudHSM keys."** You own them; lose the credentials and the keys are gone. - **"CloudHSM has a free tier."** It doesn't. ## Check yourself [#check-yourself] An HSM costs well over a dollar an hour, so instead: Create a CloudHSM cluster across two AZs and connect it to KMS as a custom key store; create KMS keys in that store and use them for S3 and EBS. ## AWS documentation [#aws-documentation] - [What is AWS CloudHSM?](https://docs.aws.amazon.com/cloudhsm/latest/userguide/introduction.html) - [Custom key stores in AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/key-store-overview.html) # DDoS resiliency best practices (/docs/security/ddos-best-practices) ## The reference architecture [#the-reference-architecture]
![A DDoS-resilient architecture: traffic from users and attackers first meets the edge, Route 53 (BP3), CloudFront (BP1) with AWS WAF (BP2) and Global Accelerator (BP1); it then reaches the Region, with API Gateway (BP4), a load balancer (BP6) and an Auto Scaling group (BP7) behind security groups and network ACLs (BP5); Shield Advanced protects CloudFront, Global Accelerator, Route 53, load balancers and Elastic IPs](/diagrams/sec-ddos-architecture.light.svg) ![A DDoS-resilient architecture: traffic from users and attackers first meets the edge, Route 53 (BP3), CloudFront (BP1) with AWS WAF (BP2) and Global Accelerator (BP1); it then reaches the Region, with API Gateway (BP4), a load balancer (BP6) and an Auto Scaling group (BP7) behind security groups and network ACLs (BP5); Shield Advanced protects CloudFront, Global Accelerator, Route 53, load balancers and Elastic IPs](/diagrams/sec-ddos-architecture.dark.svg)
Absorb attacks at the edge, scale and filter in the Region.
AWS's DDoS resiliency whitepaper numbers its best practices **BP1 to BP7**: - **BP1:** CloudFront and Global Accelerator; - **BP2:** AWS WAF; - **BP3:** Route 53; - **BP4:** API Gateway; - **BP5:** security groups and network ACLs (in the VPC); - **BP6:** Elastic Load Balancing; - **BP7:** Auto Scaling. ## Edge location mitigation (BP1, BP3) [#edge-location-mitigation-bp1-bp3] - **BP1, CloudFront:** - web application delivery at the edge; - protects from common DDoS attacks (SYN floods, UDP reflection…). - **BP1, Global Accelerator:** - access your application from the edge; - integrates with Shield for DDoS protection; - helpful if your backend isn't compatible with CloudFront (non-HTTP). - **BP3, Route 53:** - domain name resolution at the edge; - a DDoS protection mechanism. ## Best practices for DDoS mitigation [#best-practices-for-ddos-mitigation] - **Infrastructure layer defense (BP1, BP3, BP6):** - protect EC2 against high traffic; - that includes using Global Accelerator, Route 53, CloudFront, Elastic Load Balancing. - **EC2 with Auto Scaling (BP7):** helps scale in case of sudden traffic surges, including a flash crowd or a DDoS attack. - **Elastic Load Balancing (BP6):** scales with traffic increases and distributes the traffic to many EC2 instances. ## Application layer defense [#application-layer-defense] - **Detect and filter malicious web requests (BP1, BP2):** - CloudFront caches static content and serves it from edge locations, protecting your backend; - AWS WAF on CloudFront and the ALB filters and blocks requests based on request signatures; - WAF **rate-based rules** automatically block the IPs of bad actors; - use **managed rules** on WAF to block attacks based on IP reputation, or block anonymous IPs; - CloudFront can block specific geographies. - **Shield Advanced (BP1, BP2, BP6):** its automatic application layer DDoS mitigation creates, evaluates and deploys WAF rules to mitigate layer 7 attacks. ## Attack surface reduction [#attack-surface-reduction] - **Obfuscate AWS resources (BP1, BP4, BP6):** use CloudFront, API Gateway and Elastic Load Balancing to **hide your backend** resources (Lambda functions, EC2 instances). - **Security groups and network ACLs (BP5):** - filter traffic based on specific IPs at the subnet or ENI level; - Elastic IPs are protected by AWS Shield Advanced. - **Protect API endpoints (BP4):** - hide EC2, Lambda and other backends; - edge-optimized mode, or CloudFront + Regional mode (more control for DDoS); - WAF + API Gateway: burst limits, header filtering, API keys. ## Real-world examples [#real-world-examples] - **A ticketing site** expects a flash crowd at 10:00. CloudFront caches the event pages, a WAF rate-based rule limits each IP, and the Auto Scaling group behind the ALB scales out. When attack traffic arrives at the same time, the edge absorbs most of it. ## Exam tips [#exam-tips] - **"Protect a web app from DDoS"** → CloudFront (+ WAF rate-based rules) in front, ALB + Auto Scaling behind, Shield Advanced for more. - **"Non-HTTP app needs edge DDoS protection"** → Global Accelerator (+ Shield). - **"Hide the backend"** → put CloudFront, API Gateway or a load balancer in front, and lock down security groups. ## Common traps [#common-traps] - **"Expose EC2 instances directly and rely on security groups."** Put edge services and a load balancer in front to absorb and filter attacks. ## Check yourself [#check-yourself] Put AWS Global Accelerator in front (edge entry with Shield protection), add Shield Advanced for the Elastic IPs and accelerator, and keep tight security groups and NACLs on the servers. ## AWS documentation [#aws-documentation] - [AWS Best Practices for DDoS Resiliency](https://docs.aws.amazon.com/whitepapers/latest/aws-best-practices-ddos-resiliency/aws-best-practices-ddos-resiliency.html) - [Mitigation techniques](https://docs.aws.amazon.com/whitepapers/latest/aws-best-practices-ddos-resiliency/mitigation-techniques.html) # Detective, Security Hub and Artifact (/docs/security/detective-security-hub-artifact) These three services are on the exam guide's in-scope list but not in the course slides. This page is written from the AWS documentation.
![AWS Security Hub: it collects findings from GuardDuty, Inspector, Macie, AWS Config, Firewall Manager and partner tools, runs its own best-practice checks, and gives one view; findings go to EventBridge for automatic remediation, and Amazon Detective helps investigate their root cause](/diagrams/sec-security-hub.light.svg) ![AWS Security Hub: it collects findings from GuardDuty, Inspector, Macie, AWS Config, Firewall Manager and partner tools, runs its own best-practice checks, and gives one view; findings go to EventBridge for automatic remediation, and Amazon Detective helps investigate their root cause](/diagrams/sec-security-hub.dark.svg)
One place for every security finding.
## AWS Security Hub [#aws-security-hub] **[AWS Security Hub](/docs/glossary#term-aws-security-hub)** gives a **comprehensive view of your security state** across AWS accounts. - **Collects findings** from GuardDuty, Inspector, Macie, AWS Config, Firewall Manager, IAM Access Analyzer and partner tools, in one standard format. - Runs **automated best-practice checks** against standards: the **AWS Foundational Security Best Practices**, **CIS** benchmarks, **PCI DSS**, **NIST**. (The checks use **AWS Config**, which must be turned on.) - **Aggregates** across accounts (with AWS Organizations) and across Regions. - **Automation:** send findings to **EventBridge** to remediate automatically, or to ticketing and chat tools. The original service is now called **AWS Security Hub CSPM** (cloud security posture management). AWS also offers a newer, unified **AWS Security Hub** that correlates findings from GuardDuty, Inspector and others into prioritized exposures. For the exam, the idea is the same: one place to see and act on security findings. ## Amazon Detective [#amazon-detective] **[Amazon Detective](/docs/glossary#term-amazon-detective)** helps you **analyze, investigate and quickly identify the root cause** of security findings or suspicious activity. - Automatically collects data from **CloudTrail**, **VPC Flow Logs**, **GuardDuty** findings and **EKS audit logs**. - Uses machine learning, statistics and **graph theory** to build a **behavior graph** and visualizations: which IP addresses, roles and resources were involved, and what's unusual. - **Finding groups** gather related findings into one investigation. **GuardDuty finds; Detective investigates.** Start from a GuardDuty finding in Security Hub and pivot to Detective to see the whole story. ## AWS Artifact [#aws-artifact] **[AWS Artifact](/docs/glossary#term-aws-artifact)** is a self-service portal for **on-demand access to AWS compliance documents**, free of charge. - **Artifact Reports:** AWS's own audit reports, such as **SOC** reports, **PCI** attestations and **ISO** certifications. Give them to your auditors to show that the AWS infrastructure meets a standard. - **Artifact Agreements:** review, accept and track agreements with AWS, such as the **BAA** (Business Associate Addendum) needed for **HIPAA**, for one account or a whole organization. ## Real-world examples [#real-world-examples] - **A security team** turns on Security Hub across its organization and sees a single score against the AWS Foundational Security Best Practices, with failed checks such as "S3 buckets should block public access". - **An analyst** gets a GuardDuty finding for unusual API calls from a role and opens it in Detective to see every IP address and resource that role touched over the past days. - **An auditor** asks for proof of AWS's PCI compliance. The company downloads the PCI attestation from AWS Artifact. ## Exam tips [#exam-tips] - **"Central view of security findings across accounts", "check against CIS or PCI best practices"** → Security Hub. - **"Investigate the root cause of a GuardDuty finding", "visualize what happened"** → Detective. - **"Download AWS compliance reports (SOC, PCI, ISO)", "accept the HIPAA BAA"** → AWS Artifact. ## Common traps [#common-traps] - **"Detective detects threats."** GuardDuty detects; Detective investigates. - **"Artifact checks your resources for compliance."** It provides AWS's reports and agreements; for your resources, use Config or Security Hub. ## AWS documentation [#aws-documentation] - [What is AWS Security Hub CSPM?](https://docs.aws.amazon.com/securityhub/latest/userguide/what-is-securityhub.html) - [What is Amazon Detective?](https://docs.aws.amazon.com/detective/latest/userguide/what-is-detective.html) - [What is AWS Artifact?](https://docs.aws.amazon.com/artifact/latest/ug/what-is-aws-artifact.html) # GuardDuty, Inspector and Macie (/docs/security/guardduty-inspector-macie) ## Amazon GuardDuty [#amazon-guardduty]
![Amazon GuardDuty: it analyses CloudTrail events, VPC Flow Logs and DNS logs, plus optional sources such as S3 data events, EKS and runtime monitoring, malware scans, RDS logins and Lambda network activity; its findings go to EventBridge, whose rules alert through SNS or run Lambda to isolate a resource](/diagrams/sec-guardduty.light.svg) ![Amazon GuardDuty: it analyses CloudTrail events, VPC Flow Logs and DNS logs, plus optional sources such as S3 data events, EKS and runtime monitoring, malware scans, RDS logins and Lambda network activity; its findings go to EventBridge, whose rules alert through SNS or run Lambda to isolate a resource](/diagrams/sec-guardduty.dark.svg)
Threat detection from logs you already have.
**[Amazon GuardDuty](/docs/glossary#term-amazon-guardduty)** is **intelligent threat discovery** to protect your AWS account. - Uses **machine learning** algorithms, anomaly detection and third-party threat intelligence. - **One click to enable** (30-day trial), **no need to install software**. - **Input data** includes: - **CloudTrail event logs:** unusual API calls, unauthorized deployments; - CloudTrail management events: create VPC subnet, create trail… - CloudTrail S3 data events: get object, list objects, delete object… - **VPC Flow Logs:** unusual internal traffic, unusual IP addresses; - **DNS logs:** compromised EC2 instances sending encoded data within DNS queries; - **optional features:** EKS audit logs, runtime monitoring, RDS and Aurora login activity, EBS and S3 malware scans, Lambda network activity, S3 data events… - You don't need to turn on Flow Logs or DNS logging yourself: GuardDuty reads the foundational sources directly. - Set up **EventBridge rules** to be notified of findings; the rules can target **Lambda** or **SNS**. - **Can protect against cryptocurrency attacks** (it has a dedicated finding for crypto mining). GuardDuty also has **Extended Threat Detection** (free, on by default), which links separate events into one **attack sequence** finding. ## Amazon Inspector [#amazon-inspector]
![Amazon Inspector: it continuously scans EC2 instances, container images in ECR and Lambda functions for known vulnerabilities (CVEs) and network exposure, scores the risk, and sends findings to Security Hub and EventBridge](/diagrams/sec-inspector.light.svg) ![Amazon Inspector: it continuously scans EC2 instances, container images in ECR and Lambda functions for known vulnerabilities (CVEs) and network exposure, scores the risk, and sends findings to Security Hub and EventBridge](/diagrams/sec-inspector.dark.svg)
Vulnerability scanning for EC2, images and functions.
**[Amazon Inspector](/docs/glossary#term-amazon-inspector)** runs **automated security assessments**. - **For EC2 instances:** - uses the **Systems Manager (SSM) agent** (or an agentless scan of the volumes); - analyzes against **unintended network accessibility**; - analyzes the **running OS** against **known vulnerabilities**. - **For container images pushed to Amazon ECR:** assesses images as they're pushed. - **For Lambda functions:** - identifies software vulnerabilities in function **code and package dependencies**; - assesses functions as they're deployed. - **Reporting** and integration with **AWS Security Hub**; sends findings to **EventBridge**. **What does Inspector evaluate?** - Remember: **only EC2 instances, container images and Lambda functions**. - **Continuous scanning** of the infrastructure, only when needed (new package, new CVE…). - **Package vulnerabilities** (EC2, ECR and Lambda), against a database of **CVEs**. - **Network reachability** (EC2). - A **risk score** is associated with every vulnerability, for prioritization. ## Amazon Macie [#amazon-macie]
![Amazon Macie: it analyses objects in S3 buckets with machine learning and pattern matching to find sensitive data such as PII, and sends findings to EventBridge, which can alert through SNS or fix the problem with Lambda](/diagrams/sec-macie.light.svg) ![Amazon Macie: it analyses objects in S3 buckets with machine learning and pattern matching to find sensitive data such as PII, and sends findings to EventBridge, which can alert through SNS or fix the problem with Lambda](/diagrams/sec-macie.dark.svg)
Find personal data hiding in S3.
**[Amazon Macie](/docs/glossary#term-amazon-macie)** is a fully managed **data security and data privacy** service that uses **machine learning and pattern matching** to discover and protect your **sensitive data in AWS**. - Macie helps identify and alert you to **sensitive data**, such as **personally identifiable information (PII)**: names, credit card numbers, passport numbers… - It works on **S3**: an inventory of your buckets, their security (public access, encryption), and automated discovery of sensitive data in objects. - Findings go to **EventBridge** (and Security Hub) for integrations. ## Real-world examples [#real-world-examples] - **GuardDuty** raises a `CryptoCurrency:EC2/BitcoinTool` finding for an instance a developer left open; an EventBridge rule runs a Lambda function that isolates it with a quarantine security group. - **Inspector** flags a critical CVE in a container image just pushed to ECR, and the pipeline blocks the deployment. - **Macie** finds a CSV of customer emails and card numbers in a bucket meant for logs. ## Exam tips [#exam-tips] - **"Detect threats", "compromised instance", "crypto mining", "unusual API calls"** → GuardDuty. - **"Scan EC2, ECR images or Lambda for vulnerabilities (CVEs)"** → Inspector. - **"Find PII or sensitive data in S3"** → Macie. - **"Automate a response to a finding"** → EventBridge rule → Lambda or SNS. ## Common traps [#common-traps] - **"Inspector scans RDS databases or S3."** Only EC2, ECR images and Lambda. - **"Enable VPC Flow Logs first for GuardDuty."** GuardDuty reads the flow and DNS data itself. - **"Macie scans EBS volumes."** Macie is for S3. ## Check yourself [#check-yourself] GuardDuty and Inspector have free trials, but a meaningful test needs real activity, so instead: Enable GuardDuty (it analyses VPC Flow Logs and DNS logs) and create an EventBridge rule on its findings that notifies an SNS topic. Use Amazon Macie's automated sensitive data discovery on the S3 buckets, and review its findings and bucket security summary. ## AWS documentation [#aws-documentation] - [What is Amazon GuardDuty?](https://docs.aws.amazon.com/guardduty/latest/ug/what-is-guardduty.html) - [What is Amazon Inspector?](https://docs.aws.amazon.com/inspector/latest/user/what-is-inspector.html) - [What is Amazon Macie?](https://docs.aws.amazon.com/macie/latest/user/what-is-macie.html) # Security & Encryption (/docs/security) ## Why encryption [#why-encryption] Encryption makes data unreadable to anyone without the right key. On AWS you'll see three places to encrypt:
![Three kinds of encryption: in flight, TLS encrypts data between client and server; at rest server-side, the AWS service encrypts data with a data key it can use before storing it; client-side, the client encrypts data with its own key before sending it, so the storage never sees plaintext](/diagrams/sec-encryption-types.light.svg) ![Three kinds of encryption: in flight, TLS encrypts data between client and server; at rest server-side, the AWS service encrypts data with a data key it can use before storing it; client-side, the client encrypts data with its own key before sending it, so the storage never sees plaintext](/diagrams/sec-encryption-types.dark.svg)
On the wire, in the service, or before it leaves the client.
- **Encryption in flight (TLS / SSL):** - data is encrypted before sending and decrypted after receiving; - **TLS certificates** enable it (HTTPS); - it ensures no **MITM** (man-in-the-middle) attack can read or change the data on the way. - **Server-side encryption at rest:** - data is encrypted **after being received** by the server, and decrypted before being sent back; - it's stored encrypted, thanks to a key (usually a **data key**); - the encryption keys must be managed somewhere, and the server must have access to them (usually KMS). - **Client-side encryption:** - data is encrypted **by the client** and **never decrypted by the server**; - it's decrypted by a receiving client; - the server should not be able to decrypt the data; - it can use **[envelope encryption](/docs/glossary#term-envelope-encryption)**: a data key encrypts the data, and a KMS key encrypts the data key, which is stored alongside the data. ## Security services at a glance [#security-services-at-a-glance] - **Keys and encryption:** [KMS](/docs/security/kms) (managed keys), [multi-Region keys](/docs/security/kms-multi-region), [CloudHSM](/docs/security/cloudhsm) (your own dedicated hardware). - **Secrets and certificates:** [Parameter Store](/docs/security/ssm-parameter-store) (configuration and secrets), [Secrets Manager](/docs/security/secrets-manager) (secrets with rotation), [ACM](/docs/security/acm) (TLS certificates). - **Protection at the edge:** [WAF, Shield and Firewall Manager](/docs/security/waf-shield-firewall-manager), [DDoS best practices](/docs/security/ddos-best-practices). - **Threat detection and posture:** [GuardDuty, Inspector and Macie](/docs/security/guardduty-inspector-macie), [Detective, Security Hub and Artifact](/docs/security/detective-security-hub-artifact). Identity (IAM, Organizations, Cognito, IAM Identity Center) is in the [Identity & Access](/docs/identity) group, and S3 encryption options in [S3 encryption](/docs/s3/encryption). ## Exam tips [#exam-tips] - **"Encryption" for an AWS service** → almost always KMS. - **"The server must never see the plaintext"** → client-side encryption. - **"Protect data in transit"** → TLS (HTTPS), with certificates from ACM. ## Common traps [#common-traps] - **"Server-side encryption protects against the service reading the data."** The service decrypts it for you; only client-side encryption keeps the service from seeing it. ## AWS documentation [#aws-documentation] - [AWS KMS concepts](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html) - [Security, identity and compliance on AWS](https://aws.amazon.com/products/security/) # KMS multi-Region keys and encrypted sharing (/docs/security/kms-multi-region) ## Multi-Region keys [#multi-region-keys]
![KMS multi-Region keys: a primary key in us-east-1 is replicated to us-west-2, eu-west-1 and ap-southeast-2; every replica has the same key ID and key material, kept in sync, so data encrypted in one Region can be decrypted in another](/diagrams/sec-kms-multi-region.light.svg) ![KMS multi-Region keys: a primary key in us-east-1 is replicated to us-west-2, eu-west-1 and ap-southeast-2; every replica has the same key ID and key material, kept in sync, so data encrypted in one Region can be decrypted in another](/diagrams/sec-kms-multi-region.dark.svg)
One key, the same in several Regions.
**[Multi-Region keys](/docs/glossary#term-kms-multi-region-key)** are identical KMS keys in different AWS Regions that can be used **interchangeably**. - They have the **same key ID** (starting with `mrk-`), **key material**, automatic rotation… - **Encrypt in one Region and decrypt in another.** - No need to re-encrypt or make cross-Region API calls. - Multi-Region keys are **not global**: there's a **primary** and **replicas**. - Each multi-Region key is **managed independently** (its own key policy, aliases, tags). - **Use cases:** global client-side encryption, encryption on DynamoDB global tables, Aurora global databases, disaster recovery. ## DynamoDB global tables with client-side encryption [#dynamodb-global-tables-with-client-side-encryption]
![Client-side encryption with a DynamoDB global table and a multi-Region key: in us-east-1 the client encrypts the SSN attribute with the primary key and writes the item; the global table replicates the still-encrypted item to ap-southeast-2, where a client reads it and decrypts the attribute with the local replica key](/diagrams/sec-kms-mrk-dynamodb.light.svg) ![Client-side encryption with a DynamoDB global table and a multi-Region key: in us-east-1 the client encrypts the SSN attribute with the primary key and writes the item; the global table replicates the still-encrypted item to ap-southeast-2, where a client reads it and decrypts the attribute with the local replica key](/diagrams/sec-kms-mrk-dynamodb.dark.svg)
Encrypted in one Region, decrypted in another.
- Encrypt **specific attributes** client-side in a DynamoDB table with the **Amazon DynamoDB Encryption Client** (now part of the AWS Database Encryption SDK). - With **global tables**, the client-side encrypted data is replicated to other Regions. - If the multi-Region key is replicated in the same Regions as the global table, clients there can make **low-latency calls to KMS in their own Region** to decrypt. - Client-side encryption **protects specific fields** (such as a social security number) and guarantees only clients with access to the key can decrypt, **even from database admins**. The same works with **Aurora global databases** and the **AWS Encryption SDK**: encrypt a column client-side with the primary key, and decrypt it in another Region with the replica. ## S3 replication and encryption [#s3-replication-and-encryption] - **Unencrypted objects** and objects encrypted with **SSE-S3** are replicated by default. - Objects encrypted with **SSE-C** (customer-provided key) can be replicated. - For objects encrypted with **SSE-KMS**, you need to **enable the option**: - specify which KMS key encrypts the objects in the target bucket; - adapt the **KMS key policy** for the target key; - give the replication **IAM role** `kms:Decrypt` for the source key and `kms:Encrypt` for the target key; - you might get **KMS throttling errors**; ask for a Service Quotas increase if so. The slides say S3 treats multi-Region keys as independent keys, decrypting and re-encrypting each object. S3 replication now supports **multi-Region key resolution**: S3 encrypts each replica with the related multi-Region key in the destination Region. You still configure the replication options above. ## Sharing an AMI encrypted with KMS [#sharing-an-ami-encrypted-with-kms]
![Sharing an encrypted AMI: account A adds a launch permission for account B on the AMI and shares the KMS key used by its snapshots through the key policy; account B, whose role can use the key, launches an EC2 instance and can re-encrypt the volumes with its own key](/diagrams/sec-ami-sharing.light.svg) ![Sharing an encrypted AMI: account A adds a launch permission for account B on the AMI and shares the KMS key used by its snapshots through the key policy; account B, whose role can use the key, launches an EC2 instance and can re-encrypt the volumes with its own key](/diagrams/sec-ami-sharing.dark.svg)
Share the AMI and the key behind its snapshots.
1. The AMI in the source account is encrypted with a KMS key from the source account. 2. Modify the image attribute to add a **launch permission** for the target AWS account. 3. **Share the KMS keys** used to encrypt the snapshots the AMI references with the target account or IAM role. 4. The IAM role or user in the target account needs `DescribeKey`, `ReEncrypt*`, `CreateGrant` and `Decrypt` permissions on the key. 5. When launching an instance from the AMI, the target account can optionally specify a **new KMS key in its own account** to re-encrypt the volumes. See also [sharing AMIs](/docs/compute/ami#sharing-amis). ## Real-world examples [#real-world-examples] - **A payments company** encrypts card numbers client-side in a DynamoDB global table with a multi-Region key, so its US and Singapore apps can both decrypt locally, while DBAs see only ciphertext. - **A platform team** shares a golden AMI with 30 accounts: launch permissions on the AMI and a key policy on its customer managed key. ## Exam tips [#exam-tips] - **"Encrypt in one Region, decrypt in another without re-encrypting"** → KMS multi-Region keys. - **"Protect specific fields even from database admins, in a global table"** → client-side encryption + multi-Region keys. - **"Replicate SSE-KMS objects"** → enable the KMS option in replication, target key, and an IAM role with decrypt and encrypt permissions. - **"Share an encrypted AMI"** → launch permission + share the KMS key. ## Common traps [#common-traps] - **"Multi-Region keys are one global key."** They're separate keys (primary and replicas) with the same ID and material, managed independently. - **"SSE-KMS objects replicate automatically."** You must enable it. ## Check yourself [#check-yourself] A multi-Region key costs $1 a month for the primary and for each replica, so instead: Create a KMS multi-Region key in us-east-1 with a replica in eu-west-1; each Region's app decrypts with its local key. Enable replication of KMS-encrypted objects, choose the destination key, and give the replication role kms:Decrypt on the source key and kms:Encrypt on the destination key (and allow it in the key policies). ## AWS documentation [#aws-documentation] - [Multi-Region keys in AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-overview.html) - [Replicating encrypted objects](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication-config-for-kms-objects.html) - [Share an AMI with encrypted snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharing-amis-with-encrypted-snapshots.html) # AWS KMS (/docs/security/kms) ## What it is [#what-it-is] **[AWS KMS](/docs/glossary#term-aws-kms)** (Key Management Service) creates and controls **encryption keys**. - Anytime you hear "encryption" for an AWS service, it's most likely KMS. - **AWS manages the encryption keys** for you: they're kept in hardware security modules (validated to FIPS 140-3 Level 3). - Fully integrated with **IAM** for authorization. - An easy way to **control access to your data**. - **Audit** every use of a key with **CloudTrail**. - Seamlessly integrated into most AWS services (EBS, S3, RDS, SSM…). - **Never ever store your secrets in plaintext, especially in your code!** - KMS encryption is also available through API calls (SDK, CLI); - encrypted secrets can be stored in the code or environment variables. ## Key types [#key-types] **KMS keys** is the new name for KMS *customer master keys* (CMK). - **Symmetric (AES-256):** - a single encryption key used to encrypt and decrypt; - AWS services integrated with KMS use symmetric keys; - you **never get access to the key unencrypted** (you must call the KMS API to use it). - **Asymmetric (RSA and ECC key pairs):** - a public key (encrypt) and private key (decrypt) pair; - used for encrypt/decrypt, or **sign/verify**; - the **public key is downloadable**, but you can't access the private key unencrypted; - use case: encryption **outside AWS** by users who can't call the KMS API. ## Who owns the key, and what it costs [#who-owns-the-key-and-what-it-costs] - **AWS owned keys** (free): used by SSE-S3, SSE-SQS, DynamoDB's default encryption. You don't see them. - **AWS managed keys** (free to keep): named `aws/service-name`, such as `aws/rds` or `aws/ebs`. You pay for their use by the service. - **Customer managed keys** created in KMS: **$1 per month**. - **Customer managed keys imported** (your own key material): **$1 per month**. - Plus **API calls** to KMS: about **$0.03 per 10,000** calls (20,000 calls a month are free). AWS managed keys are now a **legacy key type**: AWS stopped creating them for new services in 2021 (existing ones like `aws/ebs` remain). Resources encrypted with an AWS managed key **can't be shared with other accounts**, so use a customer managed key when you need to share. Each automatic or on-demand rotation of a customer managed key also adds $1 a month, for the first two rotations only. ## Automatic key rotation [#automatic-key-rotation] - **AWS managed keys:** rotated automatically **every year**; you can't change it. - **Customer managed keys:** automatic rotation **must be enabled**; every year by default (or a custom period), and **on demand** when you want. - **Imported key material:** rotate on demand, or **manually** by creating a new key and moving an **alias** to it. The slides say imported keys can only be rotated manually with an alias. KMS now supports **on-demand rotation** for symmetric keys with imported key material. Manual rotation with an alias is still the way for asymmetric and HMAC keys, and keys in custom key stores. ## Key policies [#key-policies] - Control access to KMS keys, "similar" to S3 bucket policies. - **Difference:** you **cannot control access without them**. Every KMS key has a key policy. - **Default key policy:** - created if you don't provide a specific one; - gives the **AWS account (root)** complete access to the key, so **IAM policies** in the account can grant access. - **Custom key policy:** - define the users and roles that can **use** the key; - define who can **administer** the key; - useful for **cross-account access** to your KMS key. ## Copying snapshots across Regions [#copying-snapshots-across-regions]
![Copying an encrypted EBS snapshot across Regions: in eu-west-2 the volume and its snapshot are encrypted with KMS key A; the copy to ap-southeast-2 is re-encrypted with KMS key B, which exists in that Region, and a new volume encrypted with key B is created from it](/diagrams/sec-kms-snapshot-region.light.svg) ![Copying an encrypted EBS snapshot across Regions: in eu-west-2 the volume and its snapshot are encrypted with KMS key A; the copy to ap-southeast-2 is re-encrypted with KMS key B, which exists in that Region, and a new volume encrypted with key B is created from it](/diagrams/sec-kms-snapshot-region.dark.svg)
KMS keys are Regional, so the copy is re-encrypted.
KMS keys are **Regional** (unless you use [multi-Region keys](/docs/security/kms-multi-region)). To move an encrypted snapshot to another Region, copy it and choose a key in the destination Region: KMS **re-encrypts** it with key B. ## Copying snapshots across accounts [#copying-snapshots-across-accounts]
![Sharing an encrypted snapshot with another account: account A encrypts the snapshot with a customer managed key, adds a key policy that lets account B use the key, and shares the snapshot; account B copies it, re-encrypting with its own key, and creates a volume from the copy](/diagrams/sec-kms-snapshot-account.light.svg) ![Sharing an encrypted snapshot with another account: account A encrypts the snapshot with a customer managed key, adds a key policy that lets account B use the key, and shares the snapshot; account B copies it, re-encrypting with its own key, and creates a volume from the copy](/diagrams/sec-kms-snapshot-account.dark.svg)
Share the snapshot and the key.
1. Create a snapshot encrypted with your own KMS key (a **customer managed key**). 2. **Attach a KMS key policy** to authorize cross-account access. 3. **Share** the encrypted snapshot. 4. In the target account, create a **copy** of the snapshot, encrypted with a key in that account. 5. Create a volume from the snapshot. The key policy statement looks like this: ```json { "Sid": "Allow use of the key with destination account", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::TARGET-ACCOUNT-ID:role/ROLENAME" }, "Action": ["kms:Decrypt", "kms:CreateGrant"], "Resource": "*", "Condition": { "StringEquals": { "kms:ViaService": "ec2.REGION.amazonaws.com", "kms:CallerAccount": "TARGET-ACCOUNT-ID" } } } ``` ## Real-world examples [#real-world-examples] - **A bank** encrypts its RDS databases with customer managed keys, turns on yearly rotation, and reviews every `Decrypt` call in CloudTrail. - **A company** shares nightly encrypted EBS snapshots with its backup account: the snapshot's customer managed key has a key policy allowing that account. ## Exam tips [#exam-tips] - **"Encrypt data at rest and audit key usage"** → KMS (+ CloudTrail). - **"Users outside AWS must encrypt data they send"** → asymmetric KMS key (download the public key). - **"Share an encrypted snapshot or AMI with another account"** → customer managed key + key policy + share. - **"Copy an encrypted snapshot to another Region"** → copy and re-encrypt with a key in that Region. - **"Automatic yearly key rotation"** → enable rotation on a customer managed key. ## Common traps [#common-traps] - **"Share a snapshot encrypted with the default `aws/ebs` key."** AWS managed keys can't be shared; re-encrypt with a customer managed key first. - **"IAM policies alone control KMS access."** The key policy must allow it (the default policy enables IAM). - **"KMS keys are global."** They're Regional, except multi-Region keys. ## Hands-on lab: encrypt and decrypt with a KMS key [#hands-on-lab-encrypt-and-decrypt-with-a-kms-key] **Goal:** create a customer managed key and use it from the CLI. A customer managed key costs $1 a month, prorated by the hour, and stops billing once scheduled for deletion (the minimum waiting period is 7 days). A few API calls are within the free tier. Expect **a few cents**. Any Region works. ### Create the key [#create-the-key] **KMS → Customer managed keys → Create key**: symmetric, encrypt and decrypt, alias `saa-demo`. Add yourself as key administrator and key user. ### Encrypt [#encrypt] In CloudShell: ```bash echo -n "my secret" > secret.txt aws kms encrypt --key-id alias/saa-demo --plaintext fileb://secret.txt \ --query CiphertextBlob --output text | base64 --decode > secret.enc ``` ### Decrypt [#decrypt] ```bash aws kms decrypt --ciphertext-blob fileb://secret.enc \ --query Plaintext --output text | base64 --decode ``` No key ID is needed: the ciphertext says which key encrypted it. **Expected result:** `my secret` printed back, and both calls visible in CloudTrail event history a few minutes later. **Clean up:** **Key actions → Schedule key deletion** with a 7-day waiting period. ## AWS documentation [#aws-documentation] - [AWS KMS concepts](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html) - [AWS KMS pricing](https://aws.amazon.com/kms/pricing/) - [Rotate AWS KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html) - [Default key policy](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html) # AWS Secrets Manager (/docs/security/secrets-manager) ## What it is [#what-it-is]
![AWS Secrets Manager: the primary secret in us-east-1 rotates every 30 days with managed rotation, which also changes the RDS database password; the secret is replicated to us-west-2, where the replica is kept in sync and can be promoted to a standalone secret for disaster recovery](/diagrams/sec-secrets-manager.light.svg) ![AWS Secrets Manager: the primary secret in us-east-1 rotates every 30 days with managed rotation, which also changes the RDS database password; the secret is replicated to us-west-2, where the replica is kept in sync and can be promoted to a standalone secret for disaster recovery](/diagrams/sec-secrets-manager.dark.svg)
Secrets that rotate themselves, in every Region you need.
**[AWS Secrets Manager](/docs/glossary#term-aws-secrets-manager)** is a service **meant for storing secrets**: database credentials, API keys, OAuth tokens. - The capability to **force rotation of secrets** every X days. - **Automate generation of secrets on rotation**: - **managed rotation** for many services, with nothing to deploy; - a **Lambda function** for other secrets. - Integration with **Amazon RDS** (MySQL, PostgreSQL, Aurora) and other databases: rotation changes the password in the database and in the secret together. - Secrets are **encrypted with KMS**. - Mostly meant for **RDS integration**. - About **$0.40 per secret per month** plus $0.05 per 10,000 API calls. ## Multi-Region secrets [#multi-region-secrets] - **Replicate secrets** across multiple AWS Regions. - Secrets Manager keeps **read replicas in sync** with the primary secret. - You can **promote** a read replica secret to a **standalone** secret. - **Use cases:** multi-Region apps, **disaster recovery** strategies, multi-Region databases… ## Secrets Manager vs Parameter Store [#secrets-manager-vs-parameter-store] - **Secrets Manager:** more expensive; **automatic rotation** (managed, or a Lambda function), deep integration with RDS, Redshift, DocumentDB; KMS encryption is mandatory; multi-Region replication. - **Parameter Store:** cheaper (standard parameters are free), simple API; **no built-in rotation** (you could build it with an EventBridge schedule and Lambda); KMS encryption is optional; can read Secrets Manager secrets through the `/aws/reference/secretsmanager/` path. ## Real-world examples [#real-world-examples] - **A company** stores its Aurora admin password in Secrets Manager with 30-day managed rotation; applications fetch the current password at connection time and nobody ever sees it. - **A multi-Region app** replicates its API keys to a second Region, so the standby stack can start without manual secret copying. ## Exam tips [#exam-tips] - **"Rotate database credentials automatically"** → Secrets Manager. - **"Store RDS credentials securely, no passwords in code"** → Secrets Manager (with RDS integration). - **"Same secret in several Regions", "DR for secrets"** → multi-Region secrets. - **"Cheapest way to store config and secrets, no rotation needed"** → Parameter Store. ## Common traps [#common-traps] - **"Parameter Store and Secrets Manager are the same."** Only Secrets Manager rotates secrets for you. ## Check yourself [#check-yourself] Secrets Manager has a 30-day free trial per secret, but rotation needs a database, so instead: Store the password in Secrets Manager with automatic (managed) rotation every 30 days; applications read the secret at connection time instead of hard-coding it. ## AWS documentation [#aws-documentation] - [What is AWS Secrets Manager?](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) - [Rotate AWS Secrets Manager secrets](https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html) - [Replicate secrets across Regions](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create-manage-multi-region-secrets.html) - [AWS Secrets Manager pricing](https://aws.amazon.com/secrets-manager/pricing/) # SSM Parameter Store (/docs/security/ssm-parameter-store) ## What it is [#what-it-is] **[SSM Parameter Store](/docs/glossary#term-ssm-parameter-store)** is **secure storage for configuration and secrets**, part of [Systems Manager](/docs/management/systems-manager). - Optional, seamless **encryption with KMS** (`SecureString` parameters). - **Serverless**, scalable, durable, with an easy SDK. - **Version tracking** of configurations and secrets (the 100 most recent versions). - Security through **IAM**: an application can read only the parameters its role allows, and needs KMS permission to decrypt a `SecureString`. - **Notifications** with **EventBridge**. - **Integration with CloudFormation** (templates can read parameter values). ## Parameter hierarchy [#parameter-hierarchy]
![SSM Parameter Store hierarchy: parameters are organised as paths such as /my-department/my-app/dev/db-url; the dev Lambda function reads everything under the dev path and the prod function everything under the prod path with GetParametersByPath; SecureString values are decrypted with KMS if IAM allows it](/diagrams/sec-parameter-store.light.svg) ![SSM Parameter Store hierarchy: parameters are organised as paths such as /my-department/my-app/dev/db-url; the dev Lambda function reads everything under the dev path and the prod function everything under the prod path with GetParametersByPath; SecureString values are decrypted with KMS if IAM allows it](/diagrams/sec-parameter-store.dark.svg)
Organise parameters like folders.
- Store parameters in a **path** hierarchy: `/my-department/my-app/dev/db-url`, `/my-department/my-app/prod/db-password`… - Read one with `GetParameters`, or a whole branch with **`GetParametersByPath`**. - IAM policies can allow a path (`/my-department/my-app/dev/*`), so dev code can't read prod secrets. - Special paths: - **`/aws/reference/secretsmanager/`** reads a Secrets Manager secret through Parameter Store; - **public parameters** published by AWS, such as `/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64` for the latest Amazon Linux AMI ID. ## Standard and advanced tiers [#standard-and-advanced-tiers] **Standard:** - up to **10,000** parameters per account and Region; - values up to **4 KB**; - **no** parameter policies; - **free** (no storage charge). **Advanced:** - up to **100,000** parameters; - values up to **8 KB**; - **parameter policies** available; - **$0.05 per advanced parameter per month**. You can upgrade a parameter from standard to advanced, but not back. ## Parameter policies (advanced parameters) [#parameter-policies-advanced-parameters] - Assign a **TTL** to a parameter (an expiration date), to force updating or deleting sensitive data such as passwords. - You can assign **multiple policies** at a time: - **Expiration:** deletes the parameter at a set date and time; - **ExpirationNotification:** sends an **EventBridge** event before expiry (for example 15 days before); - **NoChangeNotification:** sends an EventBridge event if the parameter hasn't changed for a while (for example 20 days). ```json { "Type": "ExpirationNotification", "Version": "1.0", "Attributes": { "Before": "15", "Unit": "Days" } } ``` ## Real-world examples [#real-world-examples] - **A Lambda function** reads its database URL from `/shop/orders/prod/db-url` at start-up; the same code reads `/shop/orders/dev/…` in dev, picked by an environment variable. - **A launch template** uses the public parameter for the latest Amazon Linux AMI, so new instances always get the current image. ## Exam tips [#exam-tips] - **"Store configuration and secrets centrally, encrypted, cheaply"** → Parameter Store (`SecureString`). - **"Organise config per environment"** → parameter hierarchy + `GetParametersByPath` + IAM by path. - **"Latest AMI ID"** → Parameter Store public parameters. - **"Values over 4 KB" or "expiry notifications"** → advanced tier. ## Common traps [#common-traps] - **"Parameter Store rotates database passwords automatically."** That's Secrets Manager. - **"Parameter policies work on standard parameters."** Advanced tier only. ## Hands-on lab: a SecureString parameter [#hands-on-lab-a-securestring-parameter] **Goal:** store an encrypted parameter and read it back. Standard parameters are free, and `SecureString` uses the free AWS managed key `aws/ssm`. Any Region works. ### Create parameters [#create-parameters] In CloudShell: ```bash aws ssm put-parameter --name /saa/app/dev/db-url --type String --value "dev-db.example.com" aws ssm put-parameter --name /saa/app/dev/db-password --type SecureString --value "S3cret!" ``` ### Read them [#read-them] ```bash aws ssm get-parameters-by-path --path /saa/app/dev aws ssm get-parameters-by-path --path /saa/app/dev --with-decryption ``` **Expected result:** the first call shows the password encrypted; the second shows it decrypted. **Clean up:** `aws ssm delete-parameters --names /saa/app/dev/db-url /saa/app/dev/db-password` ## AWS documentation [#aws-documentation] - [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) - [Managing parameter tiers](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) - [Assigning parameter policies](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html) # WAF, Shield and Firewall Manager (/docs/security/waf-shield-firewall-manager)
![AWS WAF, Shield and Firewall Manager: WAF filters layer 7 requests with rules such as IP sets, SQL injection, cross-site scripting, geo match and rate limits; Shield protects against DDoS, Standard for free at layers 3 and 4, Advanced adding layer 7 mitigation and a response team; Firewall Manager applies WAF, Shield, security group and Network Firewall policies across an organization](/diagrams/sec-waf-shield-fm.light.svg) ![AWS WAF, Shield and Firewall Manager: WAF filters layer 7 requests with rules such as IP sets, SQL injection, cross-site scripting, geo match and rate limits; Shield protects against DDoS, Standard for free at layers 3 and 4, Advanced adding layer 7 mitigation and a response team; Firewall Manager applies WAF, Shield, security group and Network Firewall policies across an organization](/diagrams/sec-waf-shield-fm.dark.svg)
Three services that work together.
## AWS WAF [#aws-waf] **[AWS WAF](/docs/glossary#term-aws-waf)** (Web Application Firewall) protects your web applications from **common web exploits (layer 7)**. - **Layer 7 is HTTP** (vs layer 4, which is TCP/UDP). - **Deploy on:** - **Application Load Balancer**; - **API Gateway** (REST APIs); - **CloudFront**; - **AppSync** GraphQL API; - **Cognito user pool**; - and newer targets such as App Runner, Verified Access and Amplify. - Define **web ACL** (web access control list) rules: - **IP sets:** up to **10,000 IP addresses** each; use multiple rules for more; - HTTP headers, HTTP body or URI strings: protect from common attacks such as **SQL injection** and **cross-site scripting (XSS)**; - **size constraints**, **geo match** (block countries); - **rate-based rules** (count occurrences of events), **for DDoS protection**. - Web ACLs are **Regional**, except for CloudFront (global, managed in us-east-1). - A **rule group** is a reusable set of rules you can add to a web ACL. AWS and partners sell **managed rule groups** (for example Bot Control, known bad inputs). The new WAF console calls a web ACL a **protection pack**; it's the same thing. ### Fixed IP while using WAF with a load balancer [#fixed-ip-while-using-waf-with-a-load-balancer]
![A fixed IP with AWS WAF: users reach Global Accelerator on fixed IP addresses, which forwards to an Application Load Balancer in us-east-1 with an AWS WAF web ACL attached in the same Region; the load balancer sends allowed requests to the EC2 instances](/diagrams/sec-waf-fixed-ip.light.svg) ![A fixed IP with AWS WAF: users reach Global Accelerator on fixed IP addresses, which forwards to an Application Load Balancer in us-east-1 with an AWS WAF web ACL attached in the same Region; the load balancer sends allowed requests to the EC2 instances](/diagrams/sec-waf-fixed-ip.dark.svg)
Global Accelerator for the IPs, WAF on the ALB.
- WAF does **not support the Network Load Balancer** (layer 4), which is the usual answer for fixed IPs. - Use **[Global Accelerator](/docs/edge/global-accelerator)** for fixed IPs and **WAF on the ALB**. - The web ACL must be in the **same Region as the ALB**. ## AWS Shield [#aws-shield] **DDoS:** Distributed Denial of Service, many requests at the same time to overwhelm a system. - **[AWS Shield Standard](/docs/glossary#term-aws-shield):** - **free** service, activated for **every AWS customer**; - protects from attacks such as **SYN/UDP floods**, reflection attacks and other **layer 3 / layer 4** attacks. - **AWS Shield Advanced:** - optional DDoS mitigation service, about **$3,000 per month per organization** (with a 1-year commitment); - protects against more sophisticated attacks on **EC2** (Elastic IPs), **Elastic Load Balancing**, **CloudFront**, **Global Accelerator** and **Route 53**; - **24/7 access to the AWS Shield Response Team (SRT)**; - protects against **higher fees** during usage spikes caused by DDoS (cost protection); - **automatic application layer DDoS mitigation**: automatically creates, evaluates and deploys **WAF rules** to mitigate layer 7 attacks. ## AWS Firewall Manager [#aws-firewall-manager] **[AWS Firewall Manager](/docs/glossary#term-aws-firewall-manager)** **manages rules in all accounts of an AWS Organization**. - **Security policy:** a common set of security rules: - **WAF rules** (ALB, API Gateway, CloudFront); - **Shield Advanced** (ALB, CLB, NLB, Elastic IP, CloudFront); - **security groups** for EC2, ALB and ENI resources in a VPC (and network ACLs); - **AWS Network Firewall** (VPC level); - **Route 53 Resolver DNS Firewall**; - policies are created at the **Region** level. - **Rules are applied to new resources as they're created** (good for compliance), across all and future accounts in your organization. ## WAF vs Firewall Manager vs Shield [#waf-vs-firewall-manager-vs-shield] - WAF, Shield and Firewall Manager are **used together** for comprehensive protection. - Define your web ACL rules in **WAF**. - For granular protection of your resources, **WAF alone** is the correct choice. - If you want to use WAF **across accounts**, accelerate WAF configuration, and **automate the protection of new resources**, use **Firewall Manager** with WAF. - **Shield Advanced** adds features on top of WAF, such as dedicated support from the **Shield Response Team** and advanced reporting. - If you're prone to **frequent DDoS attacks**, consider purchasing Shield Advanced. ## Real-world examples [#real-world-examples] - **An online shop** puts a WAF web ACL on its CloudFront distribution with the AWS managed SQL injection rules and a rate-based rule blocking any IP sending over 2,000 requests in 5 minutes. - **A large enterprise** uses Firewall Manager so every ALB created in any of its 200 accounts automatically gets the company's WAF rules. ## Exam tips [#exam-tips] - **"SQL injection", "cross-site scripting", "block countries", "rate limit by IP"** → AWS WAF. - **"WAF on a Network Load Balancer"** → not possible; use Global Accelerator + ALB with WAF for fixed IPs. - **"DDoS protection at no cost"** → Shield Standard (automatic). - **"DDoS response team", "cost protection", "sophisticated DDoS"** → Shield Advanced. - **"Apply WAF rules or security groups across all accounts, including new ones"** → Firewall Manager. ## Common traps [#common-traps] - **"Shield Standard has to be enabled."** It's on for everyone. - **"WAF protects against layer 4 floods."** That's Shield; WAF is layer 7. - **"Web ACLs for CloudFront are created in the distribution's Region."** CloudFront web ACLs are global (us-east-1). ## Hands-on lab: block a country with WAF [#hands-on-lab-block-a-country-with-waf] **Goal:** attach a web ACL with a geo-match rule to a resource and see it block requests. WAF bills by the hour (about $0.01 an hour per protected resource, or $5 a month per web ACL plus $1 per rule on the older pricing, prorated hourly) plus $0.60 per million requests. An hour of testing costs **a cent or two**, but you need an ALB, API Gateway REST API or CloudFront distribution to attach it to. Use the Region of that resource (or Global for CloudFront). ### Create the web ACL [#create-the-web-acl] **WAF → Web ACLs → Create web ACL**, resource type matching your resource, then **Add resource**. ### Add a geo rule [#add-a-geo-rule] **Add my own rules → Rule builder**: name `block-my-country`, statement **Originates from a country in** your own country, action **Block**. Default action **Allow**. Create. ### Test it [#test-it] Open your site or API from your browser. **Expected result:** a `403 Forbidden` response, and the blocked request counted in the web ACL's overview. **Clean up:** disassociate the resource, then delete the web ACL. ## AWS documentation [#aws-documentation] - [What is AWS WAF?](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html) - [Resources you can protect with AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/how-aws-waf-works-resources.html) - [AWS Shield Advanced overview](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-advanced-summary.html) - [AWS Firewall Manager](https://docs.aws.amazon.com/waf/latest/developerguide/fms-chapter.html) # AWS Amplify and Device Farm (/docs/serverless/amplify) ## AWS Amplify [#aws-amplify] **[AWS Amplify](/docs/glossary#term-aws-amplify)** is a set of tools and services that helps you **develop and deploy scalable full-stack web and mobile applications**. Think of it as *Elastic Beanstalk for web and mobile apps*.
![AWS Amplify: frontends built with React, Vue, Angular, Next.js, Nuxt, iOS, Android or Flutter use Amplify libraries and tools to connect to a backend of Cognito for auth, S3 for storage, REST or GraphQL APIs, Lambda and DynamoDB; Amplify Hosting builds each git push and serves it from a global CDN](/diagrams/serverless-amplify.light.svg) ![AWS Amplify: frontends built with React, Vue, Angular, Next.js, Nuxt, iOS, Android or Flutter use Amplify libraries and tools to connect to a backend of Cognito for auth, S3 for storage, REST or GraphQL APIs, Lambda and DynamoDB; Amplify Hosting builds each git push and serves it from a global CDN](/diagrams/serverless-amplify.dark.svg)
A frontend, a serverless backend, and hosting in one place.
- **Backend features:** authentication (Cognito), storage (S3), APIs (REST and GraphQL), CI/CD, pub/sub, analytics, AI/ML predictions, monitoring. - **Frontend:** connect web frameworks (React, Vue, Angular, Next.js…) and mobile apps (iOS, Android, Flutter, Ionic…) to the backend with the **Amplify libraries**. - **Amplify Hosting:** connect your source code from **GitHub, Bitbucket, GitLab** (or upload it directly). Every push is built and deployed to a **global CDN** (CloudFront), with branch environments, pull request previews and custom domains. It also hosts server-side rendered apps (Next.js, Nuxt). ## AWS Device Farm [#aws-device-farm] **[AWS Device Farm](/docs/glossary#term-aws-device-farm)** tests your **Android, iOS and web apps on real phones and tablets** hosted by AWS. - **Automated testing:** run your test suites (such as Appium) across many real devices at once, and get logs, screenshots and videos. - **Remote access:** interact with a real device from your browser, to reproduce a bug on a specific phone model. - Device Farm runs in the **us-west-2 (Oregon)** Region. Device Farm is on the exam guide's in-scope list but not in the course slides. This section is written from the AWS documentation. ## Real-world examples [#real-world-examples] - **A start-up** builds a React app with Amplify: sign-up with Cognito, file uploads to S3, a GraphQL API, and a new deployment on every push to GitHub. - **A bank** runs its mobile app's tests on 50 real Android and iOS devices in Device Farm before each release. ## Exam tips [#exam-tips] - **"Build and deploy a full-stack web or mobile app quickly, with auth, storage and APIs"** → AWS Amplify. - **"Host a static or Next.js site with CI/CD from a Git repository"** → Amplify Hosting. - **"Test a mobile app on many real devices"** → AWS Device Farm. ## Common traps [#common-traps] - **"Use Elastic Beanstalk for a mobile app backend with sign-in and storage."** Amplify is the purpose-built option. - **"Device Farm uses emulators."** It uses real, physical devices. ## Check yourself [#check-yourself] AWS Amplify: Cognito-based auth and S3 storage through the Amplify libraries, and Amplify Hosting for CI/CD from GitHub to a global CDN. ## AWS documentation [#aws-documentation] - [What is AWS Amplify Hosting?](https://docs.aws.amazon.com/amplify/latest/userguide/welcome.html) - [What is AWS Device Farm?](https://docs.aws.amazon.com/devicefarm/latest/developerguide/welcome.html) # Amazon API Gateway (/docs/serverless/api-gateway) ## What it is [#what-it-is] **[Amazon API Gateway](/docs/glossary#term-amazon-api-gateway)** is a fully managed service to create, publish and secure **APIs**. With **Lambda + API Gateway** you get a REST API with **no infrastructure to manage**. - Supports **REST** and **WebSocket** APIs (and the lighter HTTP APIs). - Handles **API versioning** (v1, v2…) and **different environments** (dev, test, prod) with stages. - Handles **security** (authentication and authorization). - Creates **API keys** and handles **request throttling** (usage plans). - **Swagger / OpenAPI import** to define APIs quickly. - **Transforms and validates** requests and responses. - **Generates SDKs** and API specifications. - **Caches** API responses (REST APIs: TTL 300 seconds by default, up to 3,600). ### REST APIs vs HTTP APIs [#rest-apis-vs-http-apis] - **REST APIs:** the full feature set: API keys and usage plans, per-client throttling, request validation, caching, AWS WAF, private endpoints, edge-optimized endpoints. - **HTTP APIs:** simpler, **cheaper** and lower latency, with JWT authorizers; Regional only, without the advanced features above. ## Integrations [#integrations]
![API Gateway integrations: a client calls a REST API on API Gateway, which handles authentication and throttling and passes requests to a Lambda function, to an HTTP endpoint such as an ALB or an on-premises server, or directly to an AWS service such as Kinesis or SQS](/diagrams/serverless-api-gateway.light.svg) ![API Gateway integrations: a client calls a REST API on API Gateway, which handles authentication and throttling and passes requests to a Lambda function, to an HTTP endpoint such as an ALB or an on-premises server, or directly to an AWS service such as Kinesis or SQS](/diagrams/serverless-api-gateway.dark.svg)
One API in front of many kinds of backend.
- **Lambda function:** invoke a Lambda function. The easy way to expose a REST API backed by Lambda (client → API Gateway → Lambda → DynamoDB). - **HTTP:** expose HTTP endpoints in the backend, such as an internal HTTP API on premises or an Application Load Balancer. Why? To add **rate limiting, caching, user authentication, API keys** and more in front of it. - **AWS service:** expose any AWS API through API Gateway, with no code in between. Examples: start a **Step Functions** workflow, post a message to **SQS**, or send records to **Kinesis Data Streams** (which can feed Data Firehose and S3). Why? To add **authentication**, **public access** and **rate control**. ## Endpoint types [#endpoint-types]
![API Gateway endpoint types: edge-optimized, the default for REST APIs, serves global clients through CloudFront edge locations; Regional serves clients in the same Region and can be combined with your own CloudFront; private is reachable only from your VPC through an interface VPC endpoint plus a resource policy](/diagrams/serverless-api-endpoints.light.svg) ![API Gateway endpoint types: edge-optimized, the default for REST APIs, serves global clients through CloudFront edge locations; Regional serves clients in the same Region and can be combined with your own CloudFront; private is reachable only from your VPC through an interface VPC endpoint plus a resource policy](/diagrams/serverless-api-endpoints.dark.svg)
Where clients reach your API from.
- **Edge-optimized** (default for REST APIs): for **global clients**. Requests are routed through **CloudFront edge locations** (better latency), but the API Gateway still lives in **only one Region**. - **Regional:** for clients in the **same Region**. You can combine it with your own CloudFront distribution for more control over caching and distribution. - **Private:** can only be accessed **from your VPC**, through an **interface VPC endpoint** (ENI). Use a **resource policy** to define access. ## Security [#security] - **User authentication** through: - **IAM roles and policies:** useful for **internal** applications and AWS clients (requests signed with SigV4); - **Cognito user pools:** identity for **external users**, for example mobile app users; - **Lambda (custom) authorizers:** your own logic, such as checking a third-party token; - **JWT authorizers** (HTTP APIs). - **Resource policies** (REST APIs) allow or deny by account, IP range or VPC endpoint; **AWS WAF** protects REST APIs from common web attacks. - **Custom domain name with HTTPS**, through **AWS Certificate Manager (ACM)**: - with an **edge-optimized** endpoint, the certificate must be in **us-east-1**; - with a **Regional** endpoint, the certificate must be in the **API Gateway's Region**; - you must set up a **CNAME or alias** record in Route 53. ## Limits and throttling [#limits-and-throttling] - **Throttling:** by default **10,000 requests per second** per account per Region across all APIs, with bursts up to 5,000. Extra requests get **429 Too Many Requests**. Usage plans set per-client limits. - **Integration timeout:** **29 seconds** by default (for Regional and private REST APIs it can now be raised). A Lambda function behind a synchronous API should finish well within it. - **Payload size:** 10 MB. ## Real-world examples [#real-world-examples] - **A mobile app** calls a REST API on API Gateway, with Cognito user pools for sign-in and Lambda + DynamoDB behind it. - **A company** puts API Gateway in front of a legacy on-premises HTTP API to add API keys, throttling and caching without changing it. - **A clickstream** is sent straight from browsers to API Gateway, which writes to Kinesis Data Streams with no Lambda in between. ## Exam tips [#exam-tips] - **"Serverless REST API"** → API Gateway + Lambda. - **"Add API keys, throttling, caching, authentication in front of an existing HTTP backend"** → API Gateway HTTP integration. - **"Send requests straight to SQS, Kinesis or Step Functions without code"** → API Gateway AWS service integration. - **"Users around the world"** → edge-optimized; **"same Region"** → Regional; **"only from inside the VPC"** → private endpoint. - **"Authenticate mobile app users"** → Cognito user pools; **"internal AWS clients"** → IAM; **"custom token logic"** → Lambda authorizer. - **"Custom domain on an edge-optimized API"** → ACM certificate in us-east-1. - **"API returns 429"** → throttling limits; **"504 after 29 seconds"** → integration timeout. ## Common traps [#common-traps] - **"Edge-optimized means the API runs in every Region."** It runs in one Region; only the entry point is at the edge. - **"ACM certificate in the API's Region for an edge-optimized custom domain."** It must be in us-east-1. - **"API Gateway can wait 15 minutes for a Lambda function."** The integration timeout is 29 seconds by default. ## Hands-on lab: a serverless API [#hands-on-lab-a-serverless-api] **Goal:** create an HTTP API that calls a Lambda function. HTTP APIs cost about $1 per million requests; a few test calls and Lambda invocations cost **far less than a cent**. Any Region works. ### Create the function [#create-the-function] **Lambda → Create function**: name `saa-hello-api`, runtime Python. Code: ```python import json def lambda_handler(event, context): return {"statusCode": 200, "body": json.dumps({"message": "Hello from Lambda"})} ``` Deploy. ### Create the API [#create-the-api] **API Gateway → Create API → HTTP API → Build**. Add integration **Lambda** → `saa-hello-api`, API name `saa-api`. Route: `GET /hello`. Keep the `$default` stage with auto-deploy. Create. ### Call it [#call-it] Copy the **Invoke URL** and open `/hello` in a browser: `{"message": "Hello from Lambda"}`. **Expected result:** a public HTTPS API backed by a function, with no servers. **Clean up:** delete the `saa-api` API and the `saa-hello-api` function (and its log group). ## AWS documentation [#aws-documentation] - [What is Amazon API Gateway?](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) - [Choose between REST APIs and HTTP APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html) - [API endpoint types for REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-endpoint-types.html) - [Control and manage access to REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html) - [Custom domain names for REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html) - [Throttle requests to your REST APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html) - [Amazon API Gateway quotas](https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html) # Serverless (/docs/serverless) ## What it is [#what-it-is] **[Serverless](/docs/glossary#term-serverless)** is a way of building applications where developers **don't manage servers** anymore. They just deploy code, or functions. - At first, serverless meant **FaaS** (Function as a Service), pioneered by **AWS Lambda**. - Today it includes anything **managed** where you don't provision capacity: databases, messaging, storage and more. - **Serverless doesn't mean there are no servers.** It means you don't manage, provision or even see them. You pay for what you use, and capacity scales by itself. ## Serverless on AWS [#serverless-on-aws] Services you've already met, and some in this group: - **AWS Lambda** (functions) and **AWS Fargate** (containers); - **DynamoDB** and **Aurora Serverless** (databases); - **Amazon S3** (storage); - **Cognito** (users), **API Gateway** (APIs); - **SNS**, **SQS**, **Data Firehose**, **Step Functions** (integration).
![A serverless web app: users load static content from Amazon S3, log in with Cognito, and call a REST API on API Gateway, which runs Lambda functions that read and write DynamoDB](/diagrams/serverless-web-app.light.svg) ![A serverless web app: users load static content from Amazon S3, log in with Cognito, and call a REST API on API Gateway, which runs Lambda functions that read and write DynamoDB](/diagrams/serverless-web-app.dark.svg)
A whole web app with no servers to manage.
A typical serverless web app: 1. Users load the **static content** (HTML, JavaScript, images) from **S3**, usually through CloudFront. 2. They **log in** with **[Cognito](/docs/identity/cognito)**. 3. The app calls a **REST API** on **API Gateway**. 4. API Gateway runs **Lambda** functions with the business logic. 5. Lambda reads and writes **DynamoDB**. Nothing runs (or costs much) when nobody uses it, and every part scales on its own. ## In this group [#in-this-group] Related serverless topics live in other groups: [DynamoDB](/docs/databases/dynamodb), [Step Functions](/docs/integration/step-functions), [Cognito](/docs/identity/cognito), [edge functions](/docs/edge/edge-functions) and [Fargate](/docs/containers/ecs#fargate-launch-type). ## Exam tips [#exam-tips] - **"No servers to manage", "pay only for what you use", "scales automatically"** → a serverless design (Lambda, API Gateway, DynamoDB, S3, Fargate). - **"Serverless REST API"** → API Gateway + Lambda (+ DynamoDB). - **"Least operational overhead"** usually points to the serverless option. ## Common traps [#common-traps] - **"Serverless means no servers at all."** AWS runs them; you just don't manage them. - **"Serverless is only Lambda."** DynamoDB, S3, SQS, SNS, Fargate and many more are serverless too. ## AWS documentation [#aws-documentation] - [Serverless on AWS](https://aws.amazon.com/serverless/) - [What is AWS Lambda?](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) # Lambda limits and concurrency (/docs/serverless/lambda-limits-concurrency) ## Limits to know (per Region) [#limits-to-know-per-region] **Execution:** - **Memory:** 128 MB to 10,240 MB (10 GB), in 1 MB steps. - **Maximum execution time (timeout):** 900 seconds (15 minutes) in the exam material; **now 1,800 seconds (30 minutes)**, see the box below. - **Environment variables:** 4 KB in total. - **Disk space in `/tmp`:** 512 MB to 10 GB. - **Concurrent executions:** 1,000 by default per account per Region (can be increased). **Deployment:** - **Deployment package (zipped):** 50 MB when uploaded directly (larger through S3). - **Unzipped deployment (code + dependencies, including layers):** 250 MB. - Use the `/tmp` directory to load other files at startup. - **Container image:** up to 10 GB. **Payloads:** 6 MB for synchronous requests and responses; 1 MB for asynchronous invocations. On **19 November 2026**, AWS doubled Lambda's maximum timeout from **15 minutes to 30 minutes** (1,800 seconds). AWS only tests a feature after it has been available for at least three months (see [how current is the exam](/docs/exam-guide#how-current-is-the-exam)), so until at least February 2027 exam questions are written around **15 minutes**. If a question says a job runs longer than 15 minutes and asks what to use instead of Lambda, the intended answer is still ECS/Fargate, Batch or Step Functions. The asynchronous payload limit also grew from 256 KB to 1 MB. AWS has also added new Lambda options newer than the course: the original function type is now called a **Lambda Event Function**, alongside **Lambda Web Functions** (HTTP servers), **Lambda MicroVMs** and **Lambda Managed Instances** (functions on EC2 capacity). They aren't on the exam yet. ## Concurrency and throttling [#concurrency-and-throttling]
![Why reserve concurrency: a traffic spike through an ALB makes function A use all 1,000 executions allowed in the account, so function B behind API Gateway and function C called by the SDK are throttled; reserved concurrency fixes it](/diagrams/serverless-throttling.light.svg) ![Why reserve concurrency: a traffic spike through an ALB makes function A use all 1,000 executions allowed in the account, so function B behind API Gateway and function C called by the SDK are throttled; reserved concurrency fixes it](/diagrams/serverless-throttling.dark.svg)
One busy function can starve all the others.
**[Concurrency](/docs/glossary#term-lambda-concurrency)** is the number of function instances running at the same moment. The account limit (1,000 by default) is **shared by all functions** in the Region. - You can set **[reserved concurrency](/docs/glossary#term-reserved-concurrency)** on a function. It's both a **limit** (the function can't use more) and a **guarantee** (the rest of the account can't take it). It's free. - Each invocation over the limit triggers a **throttle**: - **synchronous** invocation → returns a **ThrottleError (HTTP 429)**; - **asynchronous** invocation → **retried automatically**, then sent to a **dead-letter queue** (or failure destination). - For a higher account limit, open a request in Service Quotas (or a support ticket). **The problem without reserved concurrency:** a traffic spike through an ALB makes one function scale to 1,000 executions. Every other function in the account (behind API Gateway, called by the SDK) is now **throttled**. Reserving concurrency for critical functions prevents this. It also protects downstream systems, for example capping a function so it can't open too many database connections. ## Concurrency and asynchronous invocations [#concurrency-and-asynchronous-invocations] For asynchronous events (such as S3 events), if the function doesn't have enough concurrency, extra requests are throttled: - For **throttling errors (429)** and **system errors (500-series)**, Lambda **returns the event to its internal queue** and tries again for **up to 6 hours**. - The retry interval grows **exponentially**, from 1 second after the first attempt to a maximum of 5 minutes. - If the function itself returns an error, Lambda retries **twice more** by default. - Events that still fail can go to a **DLQ** (SQS or SNS) or an **on-failure destination**. ## Cold starts and provisioned concurrency [#cold-starts-and-provisioned-concurrency]
![Cold starts: a new execution environment must run the initialization code before its first request; provisioned concurrency prepares environments in advance so requests go straight to invoke; SnapStart restores a saved snapshot of an initialized function, which is much faster than a full init](/diagrams/serverless-cold-start.light.svg) ![Cold starts: a new execution environment must run the initialization code before its first request; provisioned concurrency prepares environments in advance so requests go straight to invoke; SnapStart restores a saved snapshot of an initialized function, which is much faster than a full init](/diagrams/serverless-cold-start.dark.svg)
Three ways a request can start.
- **[Cold start](/docs/glossary#term-cold-start):** - a **new instance** of the function loads its code and runs the code **outside the handler** (the init phase); - if the init is large (code, dependencies, SDK clients), this can take a while; - so the **first request** served by a new instance has **higher latency** than the rest. - **[Provisioned concurrency](/docs/glossary#term-provisioned-concurrency):** - concurrency is allocated **before** the function is invoked (in advance); - so cold starts **never happen** and all invocations have low latency; - **Application Auto Scaling** can manage it (on a schedule or a target utilization); - it costs money, while reserved concurrency doesn't. - **Note:** cold starts for functions **in a VPC** were dramatically reduced in 2019, when Lambda moved to shared network interfaces. ### Reserved vs provisioned concurrency [#reserved-vs-provisioned-concurrency] - **Reserved concurrency** caps and guarantees how many instances a function **can** run. Free. - **Provisioned concurrency** keeps a number of instances **already initialized**, ready to answer instantly. Paid. It must fit within the reserved concurrency if both are set. ## Lambda SnapStart [#lambda-snapstart] - Improves function start-up performance **up to 10×**, for **Java**, **Python** and **.NET**. - When enabled, the function starts from a **pre-initialized** state, with no initialization from scratch. - When you **publish a new version**: - Lambda initializes your function; - takes a **snapshot** of the memory and disk state of the initialized function; - **caches** the snapshot for low-latency access. - New execution environments then **restore** from the snapshot instead of running the init phase. The slides say SnapStart has **no extra cost**. That's true for **Java**; for **Python** and **.NET**, AWS charges for caching and restoring snapshots. ## Exam tips [#exam-tips] - **"Function takes longer than 15 minutes"** → not Lambda (ECS/Fargate, Batch, or split the work with Step Functions). Note the new 30-minute limit, but exam questions still use 15. - **"One function's traffic throttles other functions"** → reserved concurrency on the critical ones. - **"Limit a function to protect a database"** → reserved concurrency as a cap. - **"First requests are slow", "latency-sensitive", "no cold starts"** → provisioned concurrency (or SnapStart for Java, Python, .NET). - **"Throttled synchronous call"** → HTTP 429. **"Failed asynchronous events"** → retries, then DLQ or on-failure destination. - **"Need more than 1,000 concurrent executions"** → request a quota increase. - **"Payload over 6 MB"** → put the data in S3 and pass a reference. ## Common traps [#common-traps] - **"Reserved concurrency removes cold starts."** It only reserves capacity; provisioned concurrency keeps instances warm. - **"Concurrency limits are per function by default."** The 1,000 limit is shared across the Region. - **"Increase the timeout above the maximum."** It can't go past the limit; redesign the job. ## Check yourself [#check-yourself] Set reserved concurrency on the payment function so it always has capacity (and optionally a cap on the campaign function); request a higher account limit if needed. Turn on Lambda SnapStart (no extra cost for Java). Provisioned concurrency also works but is paid. ## AWS documentation [#aws-documentation] - [Lambda quotas](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html) - [Configure Lambda function timeout](https://docs.aws.amazon.com/lambda/latest/dg/configuration-timeout.html) - [Understanding Lambda function scaling](https://docs.aws.amazon.com/lambda/latest/dg/lambda-concurrency.html) - [Configuring reserved concurrency](https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html) - [Configuring provisioned concurrency](https://docs.aws.amazon.com/lambda/latest/dg/provisioned-concurrency.html) - [How Lambda handles errors and retries with asynchronous invocation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async-error-handling.html) - [Improving startup performance with Lambda SnapStart](https://docs.aws.amazon.com/lambda/latest/dg/snapstart.html) # Lambda networking and RDS (/docs/serverless/lambda-networking) ## Lambda by default [#lambda-by-default] By default, your Lambda function runs **outside your own VPC**, in a VPC owned by AWS. - It can reach the **public internet** and public AWS services such as DynamoDB, S3 and SQS. - It **can't reach resources inside your VPC**: a private RDS database, ElastiCache, an internal load balancer. ## Lambda in a VPC [#lambda-in-a-vpc]
![Lambda in a VPC: a Lambda function configured with a VPC creates an elastic network interface in a private subnet, in a Lambda security group, so it can reach an RDS database in the RDS security group; for internet access it needs a NAT gateway in a public subnet](/diagrams/serverless-lambda-vpc.light.svg) ![Lambda in a VPC: a Lambda function configured with a VPC creates an elastic network interface in a private subnet, in a Lambda security group, so it can reach an RDS database in the RDS security group; for internet access it needs a NAT gateway in a public subnet](/diagrams/serverless-lambda-vpc.dark.svg)
Lambda reaches private resources through an ENI in your subnet.
- You configure the function with the **VPC ID**, the **subnets** and the **security groups**. - Lambda creates an **ENI** (elastic network interface) in your subnets, and uses it to reach resources such as an RDS database. - The database's security group must allow traffic from the **Lambda security group**. - The function's role needs permission to manage those network interfaces (the managed policy `AWSLambdaVPCAccessExecutionRole`). - **Internet access:** a function in a VPC doesn't get a public IP, even in a public subnet. To reach the internet, put it in **private subnets** with a route to a **NAT gateway** in a public subnet. To reach AWS services privately, use **VPC endpoints**. See [NAT gateways](/docs/vpc/nat-instance-nat-gateway) and [VPC endpoints](/docs/vpc/vpc-endpoints-privatelink). ## Lambda with RDS Proxy [#lambda-with-rds-proxy]
![Lambda with RDS Proxy: many Lambda functions deployed in the VPC connect to RDS Proxy in a private subnet, which pools their connections to the RDS database; because the proxy is never public, the functions must be in the VPC](/diagrams/serverless-rds-proxy.light.svg) ![Lambda with RDS Proxy: many Lambda functions deployed in the VPC connect to RDS Proxy in a private subnet, which pools their connections to the RDS database; because the proxy is never public, the functions must be in the VPC](/diagrams/serverless-rds-proxy.dark.svg)
Many functions, a few pooled database connections.
If Lambda functions access a database directly, they may **open too many connections** under high load: each concurrent function opens its own. **[RDS Proxy](/docs/databases/rds-security-proxy#rds-proxy)**: - improves **scalability** by pooling and sharing database connections; - improves **availability**, cutting failover time by up to 66% and keeping connections open; - improves **security** by enforcing IAM authentication and storing credentials in Secrets Manager. **The Lambda function must be deployed in your VPC**, because **RDS Proxy is never publicly accessible**. ## Invoking Lambda from RDS and Aurora [#invoking-lambda-from-rds-and-aurora]
![Invoking Lambda from RDS for PostgreSQL or Aurora MySQL: a user registers, the database inserts the row and invokes a Lambda function, which sends a welcome email through Amazon SES; the database needs an outbound network path and IAM permission to invoke the function](/diagrams/serverless-rds-invoke-lambda.light.svg) ![Invoking Lambda from RDS for PostgreSQL or Aurora MySQL: a user registers, the database inserts the row and invokes a Lambda function, which sends a welcome email through Amazon SES; the database needs an outbound network path and IAM permission to invoke the function](/diagrams/serverless-rds-invoke-lambda.dark.svg)
The database itself calls a function.
- Invoke Lambda functions **from within your DB instance**, so you can process **data events** in the database (for example, a new row in the users table sends a welcome email). - Supported for **RDS for PostgreSQL** (the `aws_lambda` extension) and **Aurora MySQL** (the `lambda_sync` and `lambda_async` functions). - You **must allow outbound traffic** from the DB instance to Lambda: through a public route, a NAT gateway or VPC endpoints. - The DB instance needs **permission** to invoke the function: an IAM role on the database (and the function's resource-based policy where needed). ## RDS event notifications [#rds-event-notifications]
![RDS event notifications: events about the DB instance itself, such as stopped or snapshot created, are sent to Amazon SNS, whose subscribers can be SQS queues or Lambda functions, or to EventBridge, whose rules can target Lambda](/diagrams/serverless-rds-events.light.svg) ![RDS event notifications: events about the DB instance itself, such as stopped or snapshot created, are sent to Amazon SNS, whose subscribers can be SQS queues or Lambda functions, or to EventBridge, whose rules can target Lambda](/diagrams/serverless-rds-events.dark.svg)
Events about the database, not about its data.
- **[RDS event notifications](/docs/glossary#term-rds-event-notification)** tell you about the **DB instance itself**: created, stopped, started, failed over… - You get **no information about the data** in it. (For data events, invoke Lambda from the database as above, or use DynamoDB Streams with DynamoDB.) - Event categories: **DB instance**, **DB snapshot**, **DB parameter group**, **DB security group**, **RDS Proxy**, **custom engine version**. - **Near real time** (up to 5 minutes). - Send notifications to **SNS**, or subscribe to the events with **EventBridge**. ## Real-world examples [#real-world-examples] - **An order API** on Lambda reads and writes a private Aurora database through RDS Proxy, so a burst of 2,000 concurrent requests doesn't exhaust connections. - **A function in a VPC** that calls a third-party payment API reaches the internet through a NAT gateway. - **A DBA team** gets an SNS email whenever a production database fails over or a snapshot fails. ## Exam tips [#exam-tips] - **"Lambda can't connect to a private RDS database"** → configure the function with the VPC, subnets and security groups. - **"Lambda in a VPC can't reach the internet"** → private subnet + NAT gateway (or VPC endpoints for AWS services). - **"Too many database connections from Lambda"** → RDS Proxy (and the function must be in the VPC). - **"Run code when a row is inserted in RDS PostgreSQL or Aurora MySQL"** → invoke Lambda from the database. - **"Be notified when a DB instance is stopped or a snapshot completes"** → RDS event notifications to SNS or EventBridge. ## Common traps [#common-traps] - **"Put the Lambda function in a public subnet to give it internet access."** It gets no public IP; use a NAT gateway. - **"RDS event notifications tell you when data changes."** They're about the instance, not the data. - **"Lambda outside the VPC can use RDS Proxy."** The proxy is only reachable inside the VPC. ## Check yourself [#check-yourself] A VPC lab needs a NAT gateway (about $0.045 an hour) and a database, so instead: Keep the function in the private subnets with a security group the database allows, and route 0.0.0.0/0 to a NAT gateway in a public subnet for the weather API. Put RDS Proxy in front of the database and point the functions (in the VPC) at the proxy endpoint, so connections are pooled. ## AWS documentation [#aws-documentation] - [Giving Lambda functions access to resources in a VPC](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html) - [Enable internet access for VPC-connected Lambda functions](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc-internet.html) - [Invoking a Lambda function from an Aurora MySQL DB cluster](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.Lambda.html) - [Invoking a Lambda function from RDS for PostgreSQL](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL-Lambda.html) - [Overview of Amazon RDS event notification](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.overview.html) # AWS Lambda (/docs/serverless/lambda) ## What it is [#what-it-is] **[AWS Lambda](/docs/glossary#term-aws-lambda)** runs your code as **functions** in response to events, without servers.
![EC2 versus Lambda: EC2 gives virtual servers limited by RAM and CPU that run all the time and that you scale by adding or removing servers; Lambda gives virtual functions with no servers, limited to short runs, run on demand and scaled automatically](/diagrams/serverless-ec2-vs-lambda.light.svg) ![EC2 versus Lambda: EC2 gives virtual servers limited by RAM and CPU that run all the time and that you scale by adding or removing servers; Lambda gives virtual functions with no servers, limited to short runs, run on demand and scaled automatically](/diagrams/serverless-ec2-vs-lambda.dark.svg)
Servers that run all the time, or functions that run when needed.
- **Amazon EC2:** virtual servers in the cloud, limited by RAM and CPU, **running continuously**. Scaling means adding or removing servers. - **AWS Lambda:** virtual **functions**, with **no servers to manage**. Limited by **time** (short executions). Runs **on demand**. **Scaling is automatic.** ## Benefits [#benefits] - **Easy pricing:** pay per request and per compute time. The free tier covers **1,000,000 requests** and **400,000 GB-seconds** of compute every month. - **Integrated** with the whole AWS suite of services. - **Many programming languages.** - **Easy monitoring** through **CloudWatch** (logs and metrics built in). - **Easy to get more resources** per function: up to **10 GB of RAM**. - **More RAM also gives more CPU and network**: CPU is allocated in proportion to memory. ## Languages [#languages] - **Node.js** (JavaScript), **Python**, **Java**, **C#** (.NET) and PowerShell, **Ruby**. - **Custom runtimes** through the OS-only runtime and the Runtime API, for languages such as **Rust** or **Go**. - **Lambda container images:** package a function as a container image (up to 10 GB). The image must implement the **Lambda Runtime API**. For running arbitrary Docker images, **ECS or Fargate** is preferred. ## Main integrations [#main-integrations] Lambda is triggered by, or works with: - **API Gateway** (REST APIs), **Kinesis** (streams), **DynamoDB** (Streams), **S3** (events), **CloudFront** (Lambda@Edge); - **EventBridge** (events and schedules), **CloudWatch Logs**, **SNS**, **SQS**, **Cognito**. ## Example: serverless thumbnails [#example-serverless-thumbnails]
![A serverless thumbnail pipeline: a new image in Amazon S3 triggers a Lambda function that writes a thumbnail back to S3 and saves the image name, size and date to DynamoDB](/diagrams/serverless-thumbnail.light.svg) ![A serverless thumbnail pipeline: a new image in Amazon S3 triggers a Lambda function that writes a thumbnail back to S3 and saves the image name, size and date to DynamoDB](/diagrams/serverless-thumbnail.dark.svg)
An upload triggers code that does the work.
1. A new image is uploaded to **S3**. 2. The [S3 event notification](/docs/s3/event-notifications) **triggers** a Lambda function. 3. The function creates a **thumbnail** and saves it to S3, and writes the image's metadata (name, size, creation date) to **DynamoDB**. ## Example: serverless cron job [#example-serverless-cron-job] An **EventBridge** schedule triggers a Lambda function **every hour** to perform a task, such as cleaning up old records. No EC2 instance has to run all day just for a scheduled script. ## Pricing [#pricing] - **Per request:** the first **1,000,000** requests a month are free; then **$0.20 per million** requests. - **Per duration**, billed in **1 ms** increments, in **GB-seconds** (memory × time): - **400,000 GB-seconds** a month are free: that's 400,000 seconds for a 1 GB function, or 3,200,000 seconds for a 128 MB one; - after that, **$0.0000166667 per GB-second**, about **$1.00 for 60,000 GB-seconds** (x86 prices in us-east-1; Arm/Graviton functions are cheaper). - Lambda is usually **very cheap** to run, so it's very popular. The slides say "$1.00 for 600,000 GB-seconds". At AWS's published price of $0.0000166667 per GB-second, $1.00 buys about **60,000** GB-seconds. The exam won't ask you to calculate this, but remember the model: requests plus memory × duration. ## Real-world examples [#real-world-examples] - **A photo app** creates thumbnails of every upload with Lambda, paying only for the seconds each resize takes. - **A company** runs 200 small scheduled scripts as Lambda functions instead of a fleet of cron servers. - **A start-up's API** on API Gateway and Lambda costs a few dollars a month until traffic grows. ## Exam tips [#exam-tips] - **"Run code in response to events without managing servers"** → Lambda. - **"Process files as they're uploaded to S3"** → S3 event → Lambda. - **"Run a script every hour without a server"** → EventBridge schedule → Lambda. - **"Function needs more CPU"** → increase its memory. - **"Run a Docker image as a function"** → Lambda container image (if it implements the Runtime API); otherwise ECS/Fargate. ## Common traps [#common-traps] - **"Lambda for a long-running process that runs all day."** Lambda is for short executions; use EC2, ECS or Fargate. - **"Choose the number of vCPUs for a Lambda function."** You choose memory; CPU follows. ## Hands-on lab: a function triggered by S3 [#hands-on-lab-a-function-triggered-by-s3] **Goal:** create a Lambda function that logs every object uploaded to a bucket. A few invocations and a small object cost **far less than a cent**. Any Region works. ### Create the function [#create-the-function] **Lambda → Create function → Author from scratch**. Name `saa-s3-logger`, runtime **Python 3.13** (or the latest), architecture arm64. Create. Replace the code with: ```python def lambda_handler(event, context): for record in event["Records"]: print("New object:", record["s3"]["object"]["key"]) ``` Choose **Deploy**. ### Add the S3 trigger [#add-the-s3-trigger] **Add trigger → S3**, choose a lab bucket, event type **All object create events**, tick the recursive-invocation acknowledgement. Add. ### Upload and check the logs [#upload-and-check-the-logs] Upload a file to the bucket. In the function, open **Monitor → View CloudWatch logs**, then the newest log stream: you see `New object: `, plus a REPORT line with the duration and memory used (the billed time). **Expected result:** every upload runs your code within a second or two, with no servers. **Clean up:** delete the trigger and the function, and the function's log group in CloudWatch Logs. ## AWS documentation [#aws-documentation] - [What is AWS Lambda?](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) - [Lambda runtimes](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html) - [Create a Lambda function using a container image](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html) - [AWS Lambda pricing](https://aws.amazon.com/lambda/pricing/) # Serverless Application Repository (/docs/serverless/serverless-application-repository) The Serverless Application Repository is on the exam guide's in-scope list but not in the course slides. This page is written from the AWS documentation. ## What it is [#what-it-is] The **[AWS Serverless Application Repository](/docs/glossary#term-serverless-application-repository)** (SAR) is a catalogue of **ready-made serverless applications** that you can **find, deploy and publish**. - Each application is defined with an **AWS SAM** (Serverless Application Model) template: a CloudFormation-based file that describes Lambda functions, APIs, tables and their permissions. - **Deploy** an application into your account in a few clicks, from the Lambda console or the SAR console. You review the permissions it needs, set parameters, and SAR deploys it as a CloudFormation stack. - **Publish** your own applications: - **publicly**, to share them with everyone; - **privately**, within your account, with specific accounts, or across your **AWS Organization**. - Applications can be **nested** inside other SAM applications, so teams reuse common building blocks. **Use cases:** reusing common patterns (an image resizer, a Slack notifier, a log processor), and sharing approved serverless components inside a company. ## Exam tips [#exam-tips] - **"Share serverless applications across teams or accounts and deploy them easily"** → Serverless Application Repository. - **"Find and deploy a ready-made serverless app"** → Serverless Application Repository. ## Common traps [#common-traps] - **"SAR runs the applications."** It only stores and shares them; they run in your account as CloudFormation stacks. ## Check yourself [#check-yourself] Publish it to the AWS Serverless Application Repository as a SAM application shared with the organization; teams deploy it from the Lambda console. ## AWS documentation [#aws-documentation] - [What is the AWS Serverless Application Repository?](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/what-is-serverlessrepo.html) # EBS encryption (/docs/storage/ebs-encryption) ## What it is [#what-it-is] EBS can **encrypt** volumes and snapshots with keys from [AWS KMS](/docs/glossary#term-aws-kms) (Key Management Service), using AES-256. When you create an encrypted volume: - **data at rest** inside the volume is encrypted; - **data in flight** between the instance and the volume is encrypted; - **all snapshots** of the volume are encrypted; - **all volumes created from those snapshots** are encrypted. Encryption and decryption happen **transparently** on the EC2 host: the operating system and applications don't change, and the effect on latency is minimal. Every instance type supports it, and it costs nothing extra (beyond KMS key use if you create your own key; the AWS-managed `aws/ebs` key is free). ## Encryption by default [#encryption-by-default] You can turn on **EBS encryption by default** in the EC2 settings. Every **new** volume and snapshot copy in that **Region** is then encrypted automatically. It's a per-Region account setting and doesn't change volumes that already exist. Many companies turn it on in every Region on day one. ## Encrypting an unencrypted volume [#encrypting-an-unencrypted-volume] You can't switch encryption on for an existing volume. Instead, copy the data through a snapshot:
![Snapshot the unencrypted volume, copy the snapshot with encryption on using a KMS key, create an encrypted volume from it and attach it](/diagrams/storage-encrypt-volume.light.svg) ![Snapshot the unencrypted volume, copy the snapshot with encryption on using a KMS key, create an encrypted volume from it and attach it](/diagrams/storage-encrypt-volume.dark.svg)
Encryption happens on the way through a snapshot.
1. Create an EBS **snapshot** of the unencrypted volume. 2. **Copy** the snapshot and tick **encrypt**, choosing a KMS key. The copy is encrypted. 3. Create a **new volume** from the encrypted snapshot. It's encrypted too. 4. **Attach** the encrypted volume to the original instance (swap it in place of the old one), then delete the old volume. **Shortcut:** step 2 isn't strictly needed. You can create an encrypted volume **directly from the unencrypted snapshot** by turning on encryption when you create the volume. Two related rules: - A snapshot of an encrypted volume is always encrypted; you can't make an unencrypted copy. - You can't change the KMS key of an existing volume or snapshot, but a **snapshot copy** can use a different key. That's also how you re-key, or share encrypted snapshots with another account using a key it can use. ## Exam tips [#exam-tips] - **"Encrypt an existing unencrypted EBS volume"** → snapshot, copy (or restore) with encryption, create a new volume, swap it in. - **"Make sure all new EBS volumes are encrypted"** → turn on EBS encryption by default in each Region (and enforce it with an SCP or AWS Config rule). - **What's encrypted** with an encrypted volume: data at rest, data in transit to the instance, snapshots, and volumes made from those snapshots. ## Common traps [#common-traps] - **"Tick encrypt on the existing volume."** Not possible; go through a snapshot. - **"Encryption needs changes in the application."** It's transparent to the OS and apps. - **"Encryption by default encrypts my old volumes."** Only new ones. ## Hands-on lab: encrypt a volume through a snapshot [#hands-on-lab-encrypt-a-volume-through-a-snapshot] **Goal:** turn an unencrypted volume into an encrypted one. Two 10 GiB gp3 volumes and two small snapshots for under an hour: about a cent. The AWS-managed key `aws/ebs` is free. ### Check the account setting [#check-the-account-setting] In the EC2 console, open **Dashboard → Account attributes → Data protection and security**. Note whether **EBS encryption** by default is on. If it is, the volume in the next step will already be encrypted; that's fine, just read along. ### Create an unencrypted volume [#create-an-unencrypted-volume] **Volumes → Create volume**: gp3, 10 GiB, encryption **off**, tag `Project=saa-lab`. Its **Encryption** column says *Not encrypted*. ### Snapshot and copy with encryption [#snapshot-and-copy-with-encryption] Create a snapshot of it. When it's *Completed*, select it and **Actions → Copy snapshot**: tick **Encrypt this snapshot**, KMS key `aws/ebs`. The copy shows *Encrypted*. ### Create the encrypted volume [#create-the-encrypted-volume] From the encrypted copy, **Actions → Create volume from snapshot** in any AZ. The new volume is *Encrypted*, and its KMS key is `aws/ebs`. **Expected result:** the same data in a volume that's now encrypted. **Clean up:** delete both volumes and both snapshots. ## AWS documentation [#aws-documentation] - [Amazon EBS encryption](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-encryption.html) - [Enable Amazon EBS encryption by default](https://docs.aws.amazon.com/ebs/latest/userguide/encryption-by-default.html) - [Copy an Amazon EBS snapshot](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-copy-snapshot.html) # EBS Multi-Attach (/docs/storage/ebs-multi-attach) ## What it is [#what-it-is] Normally an EBS volume belongs to one instance. **[Multi-Attach](/docs/glossary#term-multi-attach)** lets you attach the **same Provisioned IOPS volume (io1 or io2)** to **several EC2 instances in the same AZ** at once. Each instance gets **full read and write** access to the high-performance volume. It's built for **clustered applications** that coordinate their own writes, so that if one node fails, another already has the disk attached and takes over at once. Examples are Linux clusters such as Teradata, and Windows Server Failover Clusters. ## How it works [#how-it-works]
![Three instances in AZ 1 share one io2 volume with Multi-Attach; an instance in AZ 2 can't attach](/diagrams/storage-multi-attach.light.svg) ![Three instances in AZ 1 share one io2 volume with Multi-Attach; an instance in AZ 2 can't attach](/diagrams/storage-multi-attach.dark.svg)
One volume, many instances, one AZ.
- Turn on **Multi-Attach** when you create the volume (or later, while it's detached). - Attach it to **up to 16 instances** built on the **Nitro System**, all in the volume's AZ. - Every instance can read and write. EBS doesn't stop two instances writing the same blocks: **the application must manage concurrent writes**. - Use a **cluster-aware file system** (such as GFS2 or OCFS2). Ordinary file systems like **XFS and EXT4 aren't** designed for this, and will corrupt data if several instances mount them for writing. - Multi-Attach volumes **can't be boot volumes**, and there's no extra charge for the feature. ## When not to use it [#when-not-to-use-it] If you just want many servers to **share files**, Multi-Attach is the wrong tool: use [Amazon EFS](/docs/storage/efs) (Linux) or [FSx](/docs/storage/fsx) (Windows and others), which handle locking for you and work across AZs. ## Exam tips [#exam-tips] - **"Attach the same EBS volume to multiple instances"** → Multi-Attach, **io1/io2 only**, **same AZ**, **up to 16** instances. - **"Clustered application needs shared block storage for high availability"** → io2 with Multi-Attach. - **"Many web servers share files across AZs"** → EFS, not Multi-Attach. ## Common traps [#common-traps] - **"Multi-Attach a gp3 volume."** Only io1 and io2 support it. - **"Multi-Attach across AZs."** All instances must be in the volume's AZ. - **"Format it with XFS and mount it on all instances."** Needs a cluster-aware file system. ## Hands-on lab: one volume, two instances [#hands-on-lab-one-volume-two-instances] **Goal:** attach one io2 volume to two instances at the same time and see it on both. A 4 GiB io2 volume with 100 IOPS costs about $7 a month in total, prorated by the second: about a cent for an hour. Plus two `t3.micro` instances (about $0.04 an hour). Delete the volume as soon as you're done. ### Launch two instances in one AZ [#launch-two-instances-in-one-az] Launch two `t3.micro` instances (`saa-ma-1`, `saa-ma-2`, tag `Project=saa-lab`) in the **same subnet**, so they're in the same AZ. T3 instances are Nitro-based. ### Create a Multi-Attach volume [#create-a-multi-attach-volume] **Volumes → Create volume**: type **io2**, size **4 GiB**, IOPS **100**, the same AZ, and tick **Enable Multi-Attach**. Tag `Project=saa-lab`. ### Attach it twice [#attach-it-twice] **Actions → Attach volume** to `saa-ma-1`, then again to `saa-ma-2`. The volume's **Attached resources** lists both instances. ### See it on both [#see-it-on-both] Connect to each instance and run `lsblk`: the same 4G disk appears on both. Don't create a normal file system and write from both; that's exactly what a cluster-aware file system is for. **Expected result:** one EBS volume attached to two running instances. **Clean up:** detach the volume from both instances, delete it, and terminate both instances. ## AWS documentation [#aws-documentation] - [Attach an EBS volume to multiple EC2 instances using Multi-Attach](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-volumes-multi.html) # EBS snapshots (/docs/storage/ebs-snapshots) ## What it is [#what-it-is] An [EBS snapshot](/docs/glossary#term-ebs-snapshot) is a **point-in-time backup** of an EBS volume. You can restore it later as a new volume, in any AZ of the Region, or copy it to another Region. - Snapshots are **incremental**: the first one copies every used block, later ones only the blocks that changed since. That makes them quick and cheap. - They're stored in **Amazon S3** behind the scenes (you can't see them in the S3 console), replicated across all AZs of the Region. - You **don't have to detach** the volume to take a snapshot, but it's recommended (or at least pause writes), so the data is consistent. - AWS doesn't back up volumes for you. Schedule snapshots with **[Amazon Data Lifecycle Manager](/docs/glossary#term-amazon-data-lifecycle-manager)** or **AWS Backup**. ## Moving a volume to another AZ [#moving-a-volume-to-another-az]
![A volume in us-east-1a is snapshotted; the snapshot is stored Regionally; it's restored as a new volume in us-east-1b](/diagrams/storage-snapshot-move.light.svg) ![A volume in us-east-1a is snapshotted; the snapshot is stored Regionally; it's restored as a new volume in us-east-1b](/diagrams/storage-snapshot-move.dark.svg)
Snapshots are Regional, so they cross AZs.
1. Take a **snapshot** of the volume in `us-east-1a`. 2. The snapshot lives at **Region level**, in S3 across all AZs. 3. **Restore** it: create a new volume from the snapshot in `us-east-1b`. It starts as an exact copy. To move data to **another Region**, first **copy** the snapshot there (you can encrypt it during the copy), then restore it. AMIs are built from snapshots, which is why [copying an AMI](/docs/compute/ami) works the same way. ### Restoring and first-read latency [#restoring-and-first-read-latency] A volume restored from a snapshot is usable at once, but its blocks are downloaded from S3 the first time each is read. The first read of every block is slow. For a database that must be fast immediately, either read every block once first (*initialising* the volume, for example with `fio` or `dd`), or use Fast Snapshot Restore. ## Snapshot features [#snapshot-features]
![Archiving moves a snapshot to a 75% cheaper tier with 24–72 h restore; deleting sends it to the Recycle Bin for 1 day to 1 year; Fast Snapshot Restore gives full speed from the first read](/diagrams/storage-snapshot-features.light.svg) ![Archiving moves a snapshot to a 75% cheaper tier with 24–72 h restore; deleting sends it to the Recycle Bin for 1 day to 1 year; Fast Snapshot Restore gives full speed from the first read](/diagrams/storage-snapshot-features.dark.svg)
Archive, Recycle Bin and Fast Snapshot Restore.
### EBS Snapshots Archive [#ebs-snapshots-archive] - Moves a snapshot to an **archive tier** that's up to **75% cheaper** to store. - Restoring it back to the standard tier takes **24 to 72 hours**. - The snapshot is converted to a **full** (not incremental) copy, and is billed for at least **90 days**. - For snapshots you must keep but rarely use: end-of-project backups, yearly compliance copies. ### Recycle Bin [#recycle-bin] - **Retention rules** keep deleted snapshots (and EBS-backed AMIs) for a period you choose, from **1 day to 1 year**, so an accidental deletion can be undone. - Rules match by tag or apply to the whole Region, and can be **locked** so nobody can shorten them. - Deleted snapshots in the bin are billed at normal snapshot rates. ### Fast Snapshot Restore (FSR) [#fast-snapshot-restore-fsr] - Volumes created from an FSR-enabled snapshot are **fully initialised** at creation: **no first-read latency**. - You turn it on per snapshot and per AZ, and pay for every hour it's on (about $0.75 an hour per snapshot per AZ). Expensive, so use it for the volumes that must be fast instantly, such as a database restored during an outage. The Recycle Bin now also covers **EBS-backed AMIs** and **EBS volumes** (volumes for 1 to 7 days). EBS also offers **snapshot lock**, which makes snapshots unchangeable and undeletable for a set time (write once, read many), for compliance. ## Pricing [#pricing] - **Standard tier:** about $0.05 per GB-month of data stored. Because snapshots are incremental, deleting an old one only frees the blocks no other snapshot needs. - **Archive tier:** about $0.0125 per GB-month, plus a charge per GB restored. - **FSR:** per hour per snapshot per AZ while enabled. ## Exam tips [#exam-tips] - **"Back up EBS volumes"**, **"automate snapshots on a schedule"** → EBS snapshots with Data Lifecycle Manager or AWS Backup. - **"Move an EBS volume to another AZ / Region"** → snapshot (copy it for another Region), then restore. - **"Cheapest way to keep snapshots for years, rarely needed"** → EBS Snapshots Archive. - **"Protect against accidental deletion of snapshots"** → Recycle Bin retention rule. - **"Restored volume must deliver full performance immediately"** → Fast Snapshot Restore. ## Common traps [#common-traps] - **"Archive a snapshot you might need in an hour."** Restoring takes 24 to 72 hours. - **"Deleting the first snapshot breaks the later ones."** No: EBS keeps any blocks later snapshots still need. - **"Snapshots are stored in my S3 bucket."** They're in S3, but in AWS-managed storage you can't browse. ## Hands-on lab: snapshot, restore in another AZ, and recover from the bin [#hands-on-lab-snapshot-restore-in-another-az-and-recover-from-the-bin] **Goal:** move a volume's data to another AZ with a snapshot, and undo a snapshot deletion with the Recycle Bin. A 10 GB gp3 volume and its snapshots cost well under a cent for an hour. Don't try the archive tier in a lab: archived snapshots are billed for at least 90 days. ### Create a source volume [#create-a-source-volume] In **Elastic Block Store → Volumes**, create a **gp3, 10 GiB** volume in `us-east-1a`, tag `Project=saa-lab`, name `saa-src`. (You don't need to attach it for this lab.) ### Take a snapshot [#take-a-snapshot] Select it, **Actions → Create snapshot**, description `saa-snap`, tag `Project=saa-lab`. In **Snapshots**, wait for *Completed*. ### Restore in another AZ [#restore-in-another-az] Select the snapshot, **Actions → Create volume from snapshot**, AZ `us-east-1b`. A new volume appears in `us-east-1b` with the same size: the data has crossed AZs. ### Set up a Recycle Bin rule [#set-up-a-recycle-bin-rule] Open the **Recycle Bin** console, **Create retention rule**: resource type **EBS snapshots**, **Apply to all resources**, retention **1 day**. Create. ### Delete and recover [#delete-and-recover] Delete `saa-snap` in **Snapshots**. In **Recycle Bin → Resources**, it's listed. Select it and **Recover**. It's back in **Snapshots**. **Expected result:** the same data in a volume in another AZ, and a deleted snapshot brought back. **Clean up:** delete both volumes. Delete the **Recycle Bin rule first**, then delete the snapshot (otherwise it goes back into the bin for a day). ## AWS documentation [#aws-documentation] - [Amazon EBS snapshots](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-snapshots.html) - [Archive Amazon EBS snapshots](https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-archive.html) - [Recycle Bin](https://docs.aws.amazon.com/ebs/latest/userguide/recycle-bin.html) - [Amazon EBS fast snapshot restore](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-fast-snapshot-restore.html) - [Initialize Amazon EBS volumes](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-initialize.html) - [Automate backups with Amazon Data Lifecycle Manager](https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-lifecycle.html) # EBS volume types (/docs/storage/ebs-volume-types) ## What it is [#what-it-is] EBS volumes come in several types with different performance and price. A volume is described by three numbers: - **Size** in GiB or TiB. - **[IOPS](/docs/glossary#term-iops)** (input/output operations per second): how many separate reads and writes per second. What matters for databases and other small, random reads and writes. - **[Throughput](/docs/glossary#term-throughput)** in MiB/s: how much data per second. What matters for big files read in order, such as logs or video. There are two families:
![SSD volumes gp3, gp2, io2 Block Express and io1 are IOPS-focused and can boot; HDD volumes st1 and sc1 are throughput-focused and can't boot](/diagrams/storage-ebs-types.light.svg) ![SSD volumes gp3, gp2, io2 Block Express and io1 are IOPS-focused and can boot; HDD volumes st1 and sc1 are throughput-focused and can't boot](/diagrams/storage-ebs-types.dark.svg)
SSD for IOPS and boot disks, HDD for cheap throughput.
**Only SSD types (gp2, gp3, io1, io2) can be boot volumes.** ## General Purpose SSD: gp3 and gp2 [#general-purpose-ssd-gp3-and-gp2] Cost-effective, low-latency storage for most workloads: boot volumes, virtual desktops, development and test environments, medium-sized databases, transactional apps. **gp3** (the current one, 1 GiB to 64 TiB): - A free baseline of **3,000 IOPS** and **125 MiB/s**, whatever the size. - Pay to raise them **independently of size**, up to **80,000 IOPS** and **2,000 MiB/s**. - About 20% cheaper per GB than gp2. The default in the console, and the right choice for almost everything. **gp2** (the older one, 1 GiB to 16 TiB): - IOPS are **tied to size**: **3 IOPS per GiB**, with a minimum of 100, up to **16,000 IOPS**. You reach the maximum at 5,334 GiB. - Small volumes can **burst** to 3,000 IOPS for a while, using credits. - To get more IOPS you must buy a bigger volume, even if you don't need the space. That's the main reason to move to gp3, which you can do live with Elastic Volumes. *Example:* a 100 GiB gp2 volume gets 300 IOPS (bursting to 3,000). A 100 GiB gp3 volume gets 3,000 IOPS all the time, for less money. ## Provisioned IOPS SSD: io2 Block Express and io1 [#provisioned-iops-ssd-io2-block-express-and-io1] For critical business applications that need **sustained, consistent IOPS**, or more than gp3 can give: large databases sensitive to storage performance, such as Oracle, SQL Server or SAP HANA. **io2 Block Express** (4 GiB to 64 TiB): - Up to **256,000 IOPS** (up to 1,000 IOPS per GiB) and **4,000 MiB/s**. - **Sub-millisecond latency**, and **99.999% durability**, 100 times more than the other types. - Supports [Multi-Attach](/docs/storage/ebs-multi-attach). **io1** (4 GiB to 16 TiB, older): - Up to **64,000 IOPS** on Nitro instances (32,000 on others), at most 50 IOPS per GiB. - IOPS are set independently of size, like io2. Also supports Multi-Attach. You pay for the size **and** for every provisioned IOPS. ## Hard disk drives: st1 and sc1 [#hard-disk-drives-st1-and-sc1] Cheap storage for large amounts of data read in big sequential chunks. 125 GiB to 16 TiB, and **never a boot volume**. - **st1 (Throughput Optimized HDD):** up to **500 MiB/s** and 500 IOPS. Big data, data warehouses, log processing, frequently accessed. - **sc1 (Cold HDD):** up to **250 MiB/s** and 250 IOPS. Data that's rarely accessed, where the **lowest cost** matters most. Since 30 April 2025, **every io2 volume is io2 Block Express**, so "io2" and "io2 Block Express" now mean the same thing. The gp3 limits in the slides (64 TiB, 80,000 IOPS, 2,000 MiB/s) are current; they were raised from 16 TiB, 16,000 IOPS and 1,000 MiB/s in 2025, so older practice questions may quote the old numbers. ## Choosing a type [#choosing-a-type] 1. **Default to gp3.** It covers boot volumes and most databases. 2. **Need more than 80,000 IOPS, sub-millisecond latency, 99.999% durability, or Multi-Attach?** io2 Block Express. 3. **Large, sequential, throughput-heavy data, and cost matters?** st1. 4. **Large, rarely read data, at the lowest price?** sc1. ## Exam tips [#exam-tips] - **"Boot volume"** → gp2, gp3, io1 or io2; never st1 or sc1. - **"Increase IOPS without increasing size"** → gp3 (or io1/io2), not gp2. - **"More than 64,000 IOPS", "mission-critical database", "sub-millisecond"** → io2 Block Express. - **"Big data, log processing, data warehouse, throughput"** → st1. - **"Infrequently accessed, lowest cost HDD"** → sc1. - **"gp2 volume needs more IOPS"** → change it to gp3 with Elastic Volumes, no downtime. ## Common traps [#common-traps] - **"Use sc1 as the root volume to save money."** HDD types can't boot. - **"A gp2 volume of 100 GiB gives 3,000 IOPS all the time."** Only while burst credits last; the baseline is 300. - **"io1 and io2 IOPS come free with the size."** Provisioned IOPS are billed separately. ## Hands-on lab: change a volume's type live [#hands-on-lab-change-a-volumes-type-live] **Goal:** change a gp2 volume to gp3 and raise its IOPS while it stays attached. A 10 GiB volume and a `t3.micro` for under an hour: a few cents. Provisioning extra gp3 IOPS above 3,000 costs extra, so this lab stays at the free baseline. ### Create a gp2 volume [#create-a-gp2-volume] Launch a `t3.micro` (`saa-types`, tag `Project=saa-lab`), then create a **gp2, 10 GiB** volume in the same AZ and attach it. On the volume's details, IOPS shows **100** (3 × 10 GiB, raised to the minimum of 100). ### Modify it [#modify-it] Select the volume, **Actions → Modify volume**: type **gp3**, IOPS **3000**, throughput **125**. Confirm. ### Watch it change [#watch-it-change] The volume's state shows *modifying*, then *optimizing*, then *completed*, while it stays attached and usable. Its IOPS are now 3,000, and its price per GB went down. **Expected result:** a volume that changed type and got 30 times the IOPS with no downtime. **Clean up:** detach and delete the volume, and terminate `saa-types`. ## AWS documentation [#aws-documentation] - [Amazon EBS volume types](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-volume-types.html) - [General Purpose SSD volumes](https://docs.aws.amazon.com/ebs/latest/userguide/general-purpose.html) - [Provisioned IOPS SSD volumes](https://docs.aws.amazon.com/ebs/latest/userguide/provisioned-iops.html) - [Throughput Optimized HDD and Cold HDD volumes](https://docs.aws.amazon.com/ebs/latest/userguide/hdd-vols.html) # EBS volumes (/docs/storage/ebs-volumes) ## What it is [#what-it-is] An [Amazon EBS](/docs/glossary#term-amazon-ebs) (Elastic Block Store) **volume** is a disk you attach to an EC2 instance while it runs. Think of it as a **network USB stick**: the instance sees an ordinary drive, but the drive actually lives on AWS storage servers and is reached over the network. - Data on a volume **persists** independently of the instance: it survives a stop, and can survive termination too. - At the basic level, a volume is attached to **one instance at a time**. (The io1 and io2 types can be shared; see [Multi-Attach](/docs/storage/ebs-multi-attach).) - A volume belongs to **one Availability Zone**. Every EC2 instance in this handbook's labs already uses one: the 8 GB root volume the operating system boots from. ## How it works [#how-it-works]
![EBS volumes attached to instances in us-east-1a and us-east-1b, with one 10 GB volume unattached](/diagrams/storage-ebs-az.light.svg) ![EBS volumes attached to instances in us-east-1a and us-east-1b, with one 10 GB volume unattached](/diagrams/storage-ebs-az.dark.svg)
Volumes attach only to instances in their own AZ.
- **It's a network drive**, not a physical disk in the server. That adds a little latency, but it means a volume can be **detached** from one instance and **attached** to another quickly. - **It's locked to an AZ.** A volume in `us-east-1a` can't attach to an instance in `us-east-1b`. To move the data, take a [snapshot](/docs/storage/ebs-snapshots) and restore it in the other AZ. Inside its AZ, AWS replicates the volume to protect against a single hardware failure. - **One instance can have many volumes**, like instance B above with a 100 GB and a 50 GB volume. A volume can also sit **unattached**, still holding its data (and still billed). - **You provision capacity**: a size in GB and, for some types, IOPS and throughput. You pay for what you provision, not for what you use. - **You can grow it later.** *Elastic Volumes* lets you increase the size, change the type, or change the IOPS while the volume stays attached and in use. After growing a volume, you extend the file system inside the OS. Volumes can't be made smaller. ## Delete on termination [#delete-on-termination] Each volume attached to an instance has a **Delete on termination** setting, which decides what happens to it when the instance is terminated: - The **root volume** is deleted by default (setting on). - **Other attached volumes** are kept by default (setting off). You can change it in the console at launch, or later with the AWS CLI. *Use case:* keep the root volume after termination, for example to investigate a failed server. ## Pricing [#pricing] - You pay per **GB-month of provisioned size**, prorated by the second, whether the volume is attached or not. In us-east-1, gp3 costs about $0.08 per GB-month, so an 8 GB root volume is about $0.64 a month. - Some types also charge for provisioned **IOPS** and **throughput** above a free baseline (see [Volume types](/docs/storage/ebs-volume-types)). - Snapshots are billed separately. The slides call a volume "only mountable to one instance at a time (at the CCP level)". That's still the rule for most types; io1 and io2 volumes can be shared with Multi-Attach, covered on its own page. AWS has also added the **Recycle Bin for EBS volumes**, so a deleted volume can be recovered for up to 7 days if you set a rule up first. ## Exam tips [#exam-tips] - **"Persistent block storage for an EC2 instance"** → EBS. - **"Move an EBS volume to another AZ"** → snapshot, then create a volume from it in the other AZ. - **"Keep the root volume when the instance is terminated"** → turn off *Delete on termination* for it. - **"Increase disk size without downtime"** → Elastic Volumes (then grow the file system). ## Common traps [#common-traps] - **"Attach the volume to an instance in another AZ."** Not possible; snapshot and restore. - **"You pay only for the GB you've written."** EBS bills the full provisioned size. - **"Shrink the volume to save money."** Volumes can only grow; to shrink, copy the data to a new, smaller volume. ## Hands-on lab: add a data volume [#hands-on-lab-add-a-data-volume] **Goal:** create a volume, attach it to an instance, put a file system on it, and move it to another instance. A 10 GB gp3 volume costs about $0.80 a month, prorated (well under a cent for an hour). Plus one or two `t3.micro` instances at about $0.02 an hour each. ### Launch an instance and note its AZ [#launch-an-instance-and-note-its-az] Launch a `t3.micro` called `saa-ebs`, Amazon Linux 2023, key pair `saa-lab-key`, tag `Project=saa-lab`. On its **Networking** tab, note the **Availability Zone**, for example `us-east-1a`. ### Create a volume [#create-a-volume] Open **Elastic Block Store → Volumes → Create volume**: type **gp3**, size **10 GiB**, the **same AZ** as the instance, tag `Project=saa-lab`. Create. ### Attach it [#attach-it] Select the volume, **Actions → Attach volume**, choose `saa-ebs`. Its state changes to *In-use*. ### Format and mount it [#format-and-mount-it] Connect with EC2 Instance Connect and run: ```bash lsblk # the new 10G disk, e.g. nvme1n1 sudo mkfs -t xfs /dev/nvme1n1 # create a file system (only on a new, empty disk) sudo mkdir /data && sudo mount /dev/nvme1n1 /data echo "hello from EBS" | sudo tee /data/hello.txt df -h /data ``` ### Detach and look [#detach-and-look] Run `sudo umount /data`, then in the console **Actions → Detach volume**. The volume shows *Available*: its data is still there, waiting for an instance in the same AZ. **Expected result:** a second disk on the instance, holding a file, that can be detached and kept independently of the instance. **Clean up:** delete the volume (**Actions → Delete volume**) and terminate `saa-ebs`. Check **Volumes** for any *Available* volumes left behind: they keep billing. ## AWS documentation [#aws-documentation] - [Amazon EBS volumes](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-volumes.html) - [Modify an Amazon EBS volume using Elastic Volumes](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-modify-volume.html) - [Preserve data when an instance is terminated](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/preserving-volumes-on-termination.html) - [Amazon EBS pricing](https://aws.amazon.com/ebs/pricing/) # EBS vs EFS vs instance store (/docs/storage/ebs-vs-efs-vs-instance-store) ## The three options [#the-three-options] EC2 instances can store data in three places. Exam questions often describe a need and ask which one fits.
![EBS attaches to one instance in one AZ and survives stops; EFS is shared by hundreds of Linux instances across AZs; instance store belongs to its instance and loses data on stop](/diagrams/storage-ebs-efs-store.light.svg) ![EBS attaches to one instance in one AZ and survives stops; EFS is shared by hundreds of Linux instances across AZs; instance store belongs to its instance and loses data on stop](/diagrams/storage-ebs-efs-store.dark.svg)
Who can use it, where it lives, and whether it lasts.
### EBS volumes [#ebs-volumes] - Attached to **one instance** at a time (except io1/io2 with Multi-Attach). - **Locked to one AZ.** To move one to another AZ: take a snapshot, then restore it there. - **Performance:** gp2 IOPS grow with size; gp3, io1 and io2 let you raise IOPS independently. - **Backups use I/O.** Snapshots read the volume, so don't run them during heavy traffic. - **Root volumes are deleted** when the instance terminates, by default (you can turn that off). - Billed for **provisioned** size. ### EFS [#efs] - **Mounted by hundreds of instances** across AZs at once. - **Linux only** (POSIX). - Shares website files (WordPress), home directories, application data. - **Higher price per GB** than EBS, but you pay only for what's stored, and **storage classes** cut the cost of cold files. ### Instance store [#instance-store] - Physical disks **inside the host**, for the instance that runs there. - **The highest IOPS and lowest latency.** - **Ephemeral**: data is lost on stop, hibernate, terminate or hardware failure. - Included in the instance price. ## Deciding in a question [#deciding-in-a-question] - **Boot disk, database on EC2, data must survive stop/start, one server** → **EBS**. - **Several servers, possibly in different AZs, need the same files** → **EFS** (Linux) or FSx (Windows and others). - **Temporary data, cache, highest performance, data can be rebuilt** → **instance store**. - **Need the same data in another AZ** → EBS snapshot and restore; or use EFS, which is already in every AZ. ## Exam tips [#exam-tips] - **"Shared across AZs"** rules out EBS and instance store. - **"Survives instance stop"** rules out instance store. - **"Lowest cost per GB for one server's disk"** → EBS (gp3, or st1/sc1 for throughput data), not EFS. - **"Millions of IOPS on one instance"** → instance store. ## Check yourself [#check-yourself] Amazon EFS, mounted by every web server through the mount target in its AZ. Instance store (storage optimized instances). The data is already replicated across nodes, so ephemeral disks are fine, and they give the highest IOPS. An EBS gp3 volume with 10,000 provisioned IOPS (gp3 lets you set IOPS without buying a bigger disk). Take a snapshot of the volume, then create a new volume from the snapshot in us-east-1c and attach it. ## AWS documentation [#aws-documentation] - [Storage options for your Amazon EC2 instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Storage.html) - [Amazon EBS volumes](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-volumes.html) - [What is Amazon EFS?](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html) - [Instance store temporary block storage](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html) # Amazon EFS (/docs/storage/efs) ## What it is [#what-it-is] [Amazon EFS](/docs/glossary#term-amazon-efs) (Elastic File System) is a **managed network file system** (NFS) that **many EC2 instances mount at the same time**, across **several AZs**. Every instance sees the same folders and files, and a file written on one is readable on the others straight away. - **Highly available and scalable**: data is stored redundantly across AZs, and the file system grows and shrinks automatically, up to petabytes. **No capacity planning**. - **Pay per use**: you pay for the GB actually stored (not provisioned), at a higher price per GB than EBS. - Works with **Linux** instances, and with containers (ECS, EKS, Fargate) and Lambda. **Not Windows**. **Use cases:** content management systems and WordPress (shared uploads), web serving, shared home directories, data sharing between apps, machine-learning training data. ## How it works [#how-it-works]
![Instances in three AZs each reach a mount target in their own AZ over NFS port 2049, all leading to one EFS file system](/diagrams/storage-efs.light.svg) ![Instances in three AZs each reach a mount target in their own AZ over NFS port 2049, all leading to one EFS file system](/diagrams/storage-efs.dark.svg)
One file system, a mount target per AZ.
1. You create a file system in a Region. EFS creates a **[mount target](/docs/glossary#term-mount-target)** (a network interface with an IP address) in a subnet of each AZ you choose. 2. Instances in each AZ **mount** the file system through their local mount target, using the **NFSv4.1** protocol on **port 2049**. 3. A **security group** on the mount targets controls which instances may connect: allow inbound NFS (2049) from the instances' security group. 4. All mount targets lead to the **same data**. It's a **POSIX** file system with the standard Linux file API: permissions, owners, file locking. IAM policies can also control access, and **access points** give each application its own directory and user. Data can be **encrypted at rest** with KMS (chosen at creation) and **in transit** with TLS (using the EFS mount helper). ## Performance settings [#performance-settings] ### Performance mode (set at creation) [#performance-mode-set-at-creation] - **General Purpose** (default): lowest latency. Web servers, CMS, home directories. AWS recommends it for all file systems. - **Max I/O**: higher latency but built for highly parallel work (big data, media processing). Now a **previous-generation** option. ### Throughput mode [#throughput-mode] - **Elastic** (default, recommended): throughput scales up and down automatically with the workload; you pay for the data read and written. Best for **spiky or unpredictable** workloads. Up to tens of GiB/s of reads per file system. - **Provisioned**: you set a throughput regardless of size, for example 1 GiB/s for a 1 TB file system. For steady, known needs. - **Bursting**: throughput grows with the amount stored (about 50 MiB/s per TB, with bursts up to 100 MiB/s), using credits. EFS scales to **thousands of concurrent NFS clients**. ## Storage classes and lifecycle [#storage-classes-and-lifecycle] EFS can move files that nobody reads to cheaper storage, using **lifecycle policies**:
![Files move from Standard to Infrequent Access after 30 days without access and to Archive after 90 days, optionally back on first access](/diagrams/storage-efs-lifecycle.light.svg) ![Files move from Standard to Infrequent Access after 30 days without access and to Archive after 90 days, optionally back on first access](/diagrams/storage-efs-lifecycle.dark.svg)
The default lifecycle policy.
- **Standard**: for frequently accessed files, with millisecond latency. - **Infrequent Access (IA)**: cheaper to store, but you pay a fee each time a file is read. For files used a few times a quarter. - **Archive**: cheaper again, for files read a few times a year or less (up to about 50% cheaper than IA). - By default, files not accessed for **30 days** move to IA and after **90 days** to Archive. You can also have files move **back to Standard on first access**. Together with the right file system type, AWS quotes savings of over 90% compared with keeping everything in Standard. ### Availability and durability [#availability-and-durability] - **Regional** file systems store data across **multiple AZs**: great for production. (The slides call this *Standard*.) - **One Zone** file systems store data in **one AZ**: cheaper, great for development. Backups are on by default, and they work with the IA storage class (*One Zone-IA*). AWS now calls the multi-AZ file system type **Regional** rather than *Standard* (*Standard* is now only the name of a storage class). **Elastic** is the default throughput mode, and **Max I/O** is marked as previous generation; AWS recommends General Purpose for every file system. Elastic throughput limits have grown well beyond the slide's 3 GiB/s reads. ## Exam tips [#exam-tips] - **"Shared file system for many Linux instances across AZs"**, **"WordPress / CMS shared content"** → EFS. - **"POSIX-compliant shared storage"**, **"NFS"** → EFS. - **"Windows file share"** → not EFS: FSx for Windows File Server. - **"Unpredictable or spiky throughput"** → Elastic throughput. **"Known, steady high throughput regardless of size"** → Provisioned. - **"Reduce cost of rarely used files"** → lifecycle policy to IA / Archive. - **"Cheapest, dev/test, single AZ is fine"** → One Zone (with One Zone-IA). - **"Instances can't mount EFS"** → check the mount target's security group allows NFS (2049). ## Common traps [#common-traps] - **"Mount EFS on Windows instances."** Not supported. - **"EFS needs capacity planning."** It grows and shrinks by itself; you pay for what's stored. - **"EFS is cheaper than EBS."** Per GB it costs several times more; it's chosen for sharing, not price. ## Hands-on lab: share files between two AZs [#hands-on-lab-share-files-between-two-azs] **Goal:** mount one EFS file system on instances in two AZs and share a file between them. EFS charges per GB stored (a few KB here, effectively free) and per GB read or written with Elastic throughput (tiny). Two `t3.micro` instances add about $0.04 an hour. ### Launch two instances in different AZs [#launch-two-instances-in-different-azs] Launch `saa-efs-a` in a subnet in `us-east-1a` and `saa-efs-b` in `us-east-1b`, Amazon Linux 2023, `t3.micro`, tag `Project=saa-lab`. Give both the same new security group `saa-efs-clients` (SSH from your IP is enough). ### Create the file system [#create-the-file-system] Open **Amazon EFS → Create file system**, name `saa-efs`, default VPC, **Regional**. Then open it, **Network → Manage**, and for each mount target replace the default security group with a new group `saa-efs-mt` that allows **NFS (2049)** from `saa-efs-clients`. ### Mount it on both instances [#mount-it-on-both-instances] On each instance (EC2 Instance Connect): ```bash sudo dnf install -y amazon-efs-utils sudo mkdir /efs sudo mount -t efs -o tls fs-XXXXXXXX:/ /efs # your file system ID ``` (The file system's **Attach** button shows the exact command.) ### Share a file [#share-a-file] On `saa-efs-a`: `echo "written in 1a" | sudo tee /efs/hello.txt`. On `saa-efs-b`: `cat /efs/hello.txt`. The file written in one AZ appears in the other. **Expected result:** two instances in different AZs reading and writing the same files. **Clean up:** terminate both instances, delete the file system (type its ID to confirm), then delete the security groups `saa-efs-mt` and `saa-efs-clients`. ## AWS documentation [#aws-documentation] - [What is Amazon Elastic File System?](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html) - [Amazon EFS performance specifications](https://docs.aws.amazon.com/efs/latest/ug/performance.html) - [Managing storage lifecycle](https://docs.aws.amazon.com/efs/latest/ug/lifecycle-management-efs.html) - [Mounting EFS file systems using the EFS mount helper](https://docs.aws.amazon.com/efs/latest/ug/efs-mount-helper.html) - [Amazon EFS pricing](https://aws.amazon.com/efs/pricing/) # Amazon FSx (/docs/storage/fsx) ## What it is [#what-it-is] [Amazon FSx](/docs/glossary#term-amazon-fsx) lets you launch **well-known, high-performance file systems** on AWS as a **fully managed service**. AWS runs the servers, storage, patching, failover and backups; you get a file system that behaves exactly like the product your applications already expect.
![The four FSx file systems: Windows File Server, Lustre, NetApp ONTAP and OpenZFS](/diagrams/storage-fsx-family.light.svg) ![The four FSx file systems: Windows File Server, Lustre, NetApp ONTAP and OpenZFS](/diagrams/storage-fsx-family.dark.svg)
Four file systems, one managed service.
## FSx for Windows File Server [#fsx-for-windows-file-server] A fully managed **Windows file share**, built on Windows Server. - Speaks **SMB** and uses the **Windows NTFS** file system. - Integrates with **Microsoft Active Directory** (AWS Managed Microsoft AD or your own), with Windows **ACLs** and **user quotas**. - Supports **DFS Namespaces**, which group shares from several file systems under one folder tree. - Can also be mounted from **Linux** instances (they speak SMB too). - Scales to tens of GB/s, millions of IOPS and hundreds of PB. - **Storage:** SSD for latency-sensitive work (databases, media processing, analytics) or HDD for broad, cheaper use (home directories, CMS). - Reachable from **on-premises** over VPN or Direct Connect. - **Single-AZ** or **Multi-AZ** (a standby file server in a second AZ, with automatic failover) for high availability. - **Automatic daily backups**, stored durably (in S3 behind the scenes). *Use for:* Windows applications, SQL Server, SharePoint, user home folders, any app that needs an SMB share. ## FSx for Lustre [#fsx-for-lustre] **Lustre** (from "Linux" and "cluster") is a **parallel distributed file system** built for large-scale computing. - For **machine learning, high-performance computing (HPC)**, video processing, financial modelling, electronic design automation. - Up to **TB/s** of throughput, millions of IOPS, sub-millisecond latency. - **Storage classes:** SSD (small, random file operations, consistently low latency), HDD (large, sequential operations), and **Intelligent-Tiering** (elastic, tiered storage for most workloads). - Can be used from on-premises servers over VPN or Direct Connect. ### Working with S3 [#working-with-s3]
![Data loads from an S3 bucket into FSx for Lustre, a compute cluster uses it through a POSIX interface, and results export back to S3](/diagrams/storage-fsx-lustre.light.svg) ![Data loads from an S3 bucket into FSx for Lustre, a compute cluster uses it through a POSIX interface, and results export back to S3](/diagrams/storage-fsx-lustre.dark.svg)
S3 as the data lake, Lustre as the fast work area.
1. Link the file system to an **S3 bucket** (a *data repository*). The bucket's objects appear as files, loaded on first access. 2. The **compute cluster** reads and writes them through FSx at full Lustre speed. 3. Results are **exported back to S3**. ### Deployment options [#deployment-options] - **Scratch:** temporary storage. Data **isn't replicated** and is lost if a file server fails. High burst performance and the lowest cost. For short-term processing. - **Persistent:** long-term storage. Data is **replicated within the AZ**, and failed file servers are replaced within minutes. For long-running processing and sensitive data. ## FSx for NetApp ONTAP [#fsx-for-netapp-ontap] Managed **NetApp ONTAP**, the storage system many companies run on-premises. - Speaks **NFS, SMB and iSCSI** (block storage over the network) from one file system. - Works with **Linux, Windows and macOS**, VMware Cloud on AWS, Amazon WorkSpaces and AppStream 2.0, and EC2, ECS and EKS. - Storage **grows and shrinks automatically**, tiering cold data to cheaper storage. - **Snapshots, replication, compression and deduplication**, and **instant point-in-time cloning** (handy for testing on a copy of production data). *Use for:* moving workloads that run on ONTAP or another NAS to AWS without changing them; "high OS compatibility". ## FSx for OpenZFS [#fsx-for-openzfs] Managed **OpenZFS**. - Speaks **NFS** (v3, v4.0, v4.1, v4.2), so Linux, Windows and macOS clients can use it. - Up to **2 million IOPS** with latencies of a few hundred microseconds. - **Snapshots, compression**, low cost, and **instant point-in-time cloning**. *Use for:* moving ZFS or other Linux file servers to AWS. FSx for Lustre now has an **Intelligent-Tiering** storage class besides SSD and HDD, and Lustre throughput reaches TB/s. FSx for OpenZFS now delivers up to 2 million IOPS (the slides say 1 million). ## Exam tips [#exam-tips] - **"Windows file share", "SMB", "NTFS", "Active Directory", "DFS"** → FSx for Windows File Server. **"Highly available"** → Multi-AZ deployment. - **"HPC", "machine learning", "parallel file system", "process S3 data at high speed"** → FSx for Lustre. - **"Temporary, short-term, cost-optimised HPC storage"** → Lustre **scratch**. **"Long-term, replicated"** → Lustre **persistent**. - **"NFS, SMB and iSCSI from one system", "move NetApp / NAS to AWS"** → FSx for NetApp ONTAP. - **"Move ZFS file servers", "instant clones over NFS"** → FSx for OpenZFS. - **Linux shared files, no special features** → EFS is usually simpler. ## Common traps [#common-traps] - **"EFS for Windows servers."** Use FSx for Windows File Server. - **"FSx for Lustre for Windows home folders."** Lustre is a Linux HPC file system. - **"Scratch file systems keep data if a server fails."** They don't replicate data. ## Check yourself [#check-yourself] FSx file systems bill by the hour from the moment they exist, with minimum sizes (for example 1.2 TiB for a Lustre file system), and FSx for Windows needs Active Directory. Instead of a lab: FSx for Windows File Server, Multi-AZ deployment, joined to the company's Active Directory (through AWS Managed Microsoft AD or the self-managed AD). FSx for Lustre, **scratch** deployment, linked to the S3 bucket as a data repository. Delete it when the job finishes. FSx for NetApp ONTAP, which supports NFS, SMB and iSCSI. ## AWS documentation [#aws-documentation] - [What is FSx for Windows File Server?](https://docs.aws.amazon.com/fsx/latest/WindowsGuide/what-is.html) - [Availability and durability: Single-AZ and Multi-AZ file systems](https://docs.aws.amazon.com/fsx/latest/WindowsGuide/high-availability-multiAZ.html) - [What is Amazon FSx for Lustre?](https://docs.aws.amazon.com/fsx/latest/LustreGuide/what-is.html) - [Deployment and storage class options for FSx for Lustre](https://docs.aws.amazon.com/fsx/latest/LustreGuide/using-fsx-lustre.html) - [What is Amazon FSx for NetApp ONTAP?](https://docs.aws.amazon.com/fsx/latest/ONTAPGuide/what-is-fsx-ontap.html) - [What is Amazon FSx for OpenZFS?](https://docs.aws.amazon.com/fsx/latest/OpenZFSGuide/what-is-fsx.html) # Storage: Block & File (/docs/storage) ## What it is [#what-it-is] Every application needs somewhere to keep data. AWS offers three kinds of storage, and they work very differently:
![Block storage (EBS, instance store) for one server, file storage (EFS, FSx) for many servers, object storage (S3, Glacier) for anyone over HTTPS](/diagrams/storage-types.light.svg) ![Block storage (EBS, instance store) for one server, file storage (EFS, FSx) for many servers, object storage (S3, Glacier) for anyone over HTTPS](/diagrams/storage-types.dark.svg)
The three kinds of storage.
- **[Block storage](/docs/glossary#term-block-storage)** is a raw disk, split into fixed-size blocks. The operating system formats it with a file system (ext4, XFS, NTFS) and uses it like a hard drive. It's attached to **one server**. On AWS: **Amazon EBS** volumes and **EC2 instance store**. - **[File storage](/docs/glossary#term-file-storage)** is a shared folder tree served over the network with a protocol such as NFS or SMB. **Many servers** read and write the same files at once. On AWS: **Amazon EFS** and **Amazon FSx**. - **[Object storage](/docs/glossary#term-object-storage)** keeps whole files (objects) with a key and metadata, read and written over HTTPS by any program. It scales without limit, but you can't edit part of an object in place. On AWS: **Amazon S3** and **S3 Glacier**, covered in the [Amazon S3](/docs/s3) group. A WordPress site might use all three. Each web server boots from its own **EBS** volume. The uploaded images that every web server must see sit on a shared **EFS** file system. Nightly backups of the database go to **S3**. ## In this group [#in-this-group] ### Block storage (EBS) [#block-storage-ebs] ### File storage [#file-storage] ### Choosing [#choosing] ## Exam tips [#exam-tips] - **"Disk for one EC2 instance", "boot volume", "database on EC2"** → EBS. - **"Shared file system for many Linux instances across AZs"** → EFS. - **"Shared file system for Windows", "SMB", "Active Directory"** → FSx for Windows File Server. - **"HPC", "parallel file system", "process data from S3 at high speed"** → FSx for Lustre. - **"Highest IOPS, temporary data, cache"** → instance store. - **"Store unlimited files, accessed over HTTP, cheaply"** → S3 (object storage). ## AWS documentation [#aws-documentation] - [Storage services on AWS (overview)](https://docs.aws.amazon.com/whitepapers/latest/aws-overview/storage-services.html) - [Choosing an AWS storage service](https://docs.aws.amazon.com/decision-guides/latest/storage-on-aws-how-to-choose/choosing-aws-storage-service.html) - [What is Amazon EBS?](https://docs.aws.amazon.com/ebs/latest/userguide/what-is-ebs.html) - [What is Amazon EFS?](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html) # Instance store (/docs/storage/instance-store) ## What it is [#what-it-is] EBS volumes are network drives: good, but limited by the network. When you need a **high-performance local disk**, some instance types come with an **[instance store](/docs/glossary#term-instance-store)**: SSD (usually NVMe) disks **physically attached to the host computer** your instance runs on. - **Much better I/O performance**: millions of IOPS on the largest storage optimized types, with very low latency. - **Included in the instance price**; you don't pay per GB. - **Ephemeral**: the data is **lost** when the instance **stops, hibernates or terminates**, or if the underlying disk or host fails. It survives a **reboot**. Only some types have instance store. They usually have a `d` in the name (`c6gd`, `m6id`) or are storage optimized (`i4i`, `i7i`, `d3`). The size is fixed by the type. ## How it compares with EBS [#how-it-compares-with-ebs]
![Instance store disks sit inside the host next to the instance, fastest but lost on stop; an EBS volume is reached over the network and survives stops](/diagrams/storage-instance-store.light.svg) ![Instance store disks sit inside the host next to the instance, fastest but lost on stop; an EBS volume is reached over the network and survives stops](/diagrams/storage-instance-store.dark.svg)
Local and fast, or networked and durable.
- **Instance store** lives inside the physical host. When the instance stops, it moves to other hardware and its old local disks are wiped, which is why the data doesn't follow it. - **EBS** lives on separate storage servers in the AZ. The instance reaches it over the network, so it can move with the instance, be detached, and be snapshotted. ## When to use it [#when-to-use-it] Instance store is good for data you can lose or rebuild: - **buffers, caches, scratch data and temporary files**; - data that's **replicated** across several instances anyway, such as a distributed database (Cassandra, Kafka) or a pool of load-balanced web servers; - very high-IOPS work that EBS can't reach. **Backups and replication are your responsibility.** There are no snapshots for instance store. ## Exam tips [#exam-tips] - **"Highest possible IOPS", "very low latency local storage"** → instance store (storage optimized types). - **"Temporary data, cache, buffer, scratch space"** → instance store. - **"Data must survive stop/start"** → EBS, not instance store. ## Common traps [#common-traps] - **"Instance store data survives a stop if you start the instance again."** It doesn't; only a reboot keeps it. - **"Snapshot the instance store."** Snapshots are for EBS; copy the data elsewhere yourself. - **"Any instance type can add instance store."** Only types that come with it. ## Hands-on lab: watch instance store data disappear [#hands-on-lab-watch-instance-store-data-disappear] **Goal:** write to an instance store disk, stop and start the instance, and see the data gone. `c6gd.medium` (Graviton, with a 59 GB NVMe instance store) costs about $0.04 an hour On-Demand in us-east-1, plus $0.005 for its public IP. Under ten cents for the lab. ### Launch an instance with instance store [#launch-an-instance-with-instance-store] Launch `saa-store`: **Amazon Linux 2023 (64-bit Arm)**, type `c6gd.medium`, key pair `saa-lab-key`, tag `Project=saa-lab`. (If it isn't offered in your AZ, try another subnet or `m6gd.medium`.) ### Find and use the local disk [#find-and-use-the-local-disk] Connect with EC2 Instance Connect: ```bash lsblk # nvme1n1, ~55G, no mount: the instance store sudo mkfs -t xfs /dev/nvme1n1 sudo mkdir /scratch && sudo mount /dev/nvme1n1 /scratch echo "temporary data" | sudo tee /scratch/file.txt ``` ### Reboot [#reboot] Reboot from the console, reconnect, and mount it again with `sudo mount /dev/nvme1n1 /scratch`. `cat /scratch/file.txt` still works: a reboot keeps the data. ### Stop and start [#stop-and-start] Stop the instance, start it, reconnect, and run `lsblk`. The disk is there but empty, with no file system: `sudo mount /dev/nvme1n1 /scratch` fails. The data is gone. **Expected result:** instance store data survives a reboot but not a stop and start. **Clean up:** terminate `saa-store`. ## AWS documentation [#aws-documentation] - [Instance store temporary block storage for EC2 instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html) - [Data persistence for Amazon EC2 instance store volumes](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-store-lifetime.html) # Storage comparison (/docs/storage/storage-comparison) ## The whole storage family [#the-whole-storage-family] This page lists every storage option the exam covers, including those taught in later groups. Each line is the one-sentence summary to remember. **Object storage** - **Amazon S3:** object storage for any amount of data, reached over HTTPS. ([Amazon S3](/docs/s3) group.) - **S3 Glacier:** object storage for archives, very cheap, slower to retrieve. ([S3 storage classes](/docs/s3/storage-classes#glacier-classes).) **Block storage** - **[EBS volumes](/docs/storage/ebs-volumes):** network storage for **one EC2 instance at a time**. - **[Instance store](/docs/storage/instance-store):** physical storage inside the host, **very high IOPS**, temporary. **File storage** - **[EFS](/docs/storage/efs):** network file system for **Linux** instances, POSIX. - **[FSx for Windows File Server](/docs/storage/fsx#fsx-for-windows-file-server):** network file system for **Windows** servers (SMB). - **[FSx for Lustre](/docs/storage/fsx#fsx-for-lustre):** **high-performance computing** Linux file system, linked to S3. - **[FSx for NetApp ONTAP](/docs/storage/fsx#fsx-for-netapp-ontap):** **broad OS compatibility** (NFS, SMB, iSCSI). - **[FSx for OpenZFS](/docs/storage/fsx#fsx-for-openzfs):** managed **ZFS** file system. **Hybrid and data transfer** ([Migration & Transfer](/docs/migration) group) - **[Storage Gateway](/docs/migration/storage-gateway):** on-premises access to cloud storage: S3 File Gateway, Volume Gateway (cached and stored), Tape Gateway (FSx File Gateway is closed to new customers). - **[Transfer Family](/docs/migration/transfer-family):** FTP, FTPS and SFTP interfaces on top of S3 or EFS. - **[DataSync](/docs/migration/datasync):** scheduled data sync from on-premises to AWS, or between AWS storage services. - **[Snowball Edge](/docs/migration/snow-family)** (and the retired Snowcone and Snowmobile): move large amounts of data to the cloud physically, on devices. **Databases** ([Databases](/docs/databases) group): for specific workloads, usually with indexing and querying. ## Which one? [#which-one]
![A decision flow: one instance's disk is EBS, shared Linux files EFS, Windows or SMB FSx for Windows, HPC FSx for Lustre, NetApp or ZFS FSx ONTAP or OpenZFS, otherwise S3](/diagrams/storage-chooser.light.svg) ![A decision flow: one instance's disk is EBS, shared Linux files EFS, Windows or SMB FSx for Windows, HPC FSx for Lustre, NetApp or ZFS FSx ONTAP or OpenZFS, otherwise S3](/diagrams/storage-chooser.dark.svg)
Ask the questions in order.
1. **A disk for one EC2 instance?** Amazon EBS; instance store if the data is temporary and speed matters most. 2. **Linux servers share files?** Amazon EFS. 3. **Windows, SMB or Active Directory?** FSx for Windows File Server. 4. **HPC or machine learning at top speed?** FSx for Lustre. 5. **Moving a NetApp or ZFS system as is?** FSx for NetApp ONTAP or FSx for OpenZFS. 6. **Otherwise**, for files at any scale reached by apps over HTTPS, backups, data lakes and static websites: Amazon S3. The slides list **Snowcone, Snowball and Snowmobile**. Snowcone and Snowmobile are retired, and **Snowball Edge is no longer available to new customers**; AWS ends support for it in commercial Regions on 31 December 2026. For new projects AWS points to **DataSync** for online transfers and the **AWS Data Transfer Terminal** (physical sites where you bring your own drives) for physical ones. Snowball may still appear in exam questions as "move petabytes without a fast network". See [Snowball Edge](/docs/migration/snow-family). ## Exam tips [#exam-tips] - **"Object", "static website", "data lake", "unlimited storage"** → S3. **"Archive, retrieve in hours"** → S3 Glacier. - **"Block storage for EC2"** → EBS; **"temporary, highest IOPS"** → instance store. - **"Shared POSIX file system"** → EFS; **"SMB / Windows"** → FSx for Windows; **"HPC / Lustre"** → FSx for Lustre. - **"On-premises apps need access to cloud storage"** → Storage Gateway. **"SFTP into S3"** → Transfer Family. **"Copy large data sets online"** → DataSync. **"Petabytes, slow or no network"** → Snowball Edge in exam answers (closed to new customers now). ## Check yourself [#check-yourself] AWS Transfer Family with an SFTP endpoint backed by an S3 bucket. Amazon EFS (Fargate tasks can mount EFS). FSx for Windows File Server. Amazon S3 (with Athena for queries, covered in the Analytics group). ## AWS documentation [#aws-documentation] - [Storage services on AWS (overview)](https://docs.aws.amazon.com/whitepapers/latest/aws-overview/storage-services.html) - [Choosing an AWS storage service](https://docs.aws.amazon.com/decision-guides/latest/storage-on-aws-how-to-choose/choosing-aws-storage-service.html) # Study path (/docs/study-path) ## Two ways to read [#two-ways-to-read] - **By service family** (the sidebar): best for review and for looking things up. All of S3 is in one place, all of networking in another. - **In course order** (this page): best while you watch the videos. Each row is one section of the course, in the order Maarek teaches it, with the notes that match. Both cover the same pages. Links appear as each group of notes is written. ## Course order [#course-order] 1. **Getting Started with AWS** (slides 14–23) → [Cloud Foundations](/docs/foundations): [overview](/docs/foundations), [global infrastructure](/docs/foundations/global-infrastructure), [Console, CLI and SDK](/docs/foundations/console-cli-sdk) 2. **AWS Identity & Access Management (IAM)** (slides 24–40) → [Identity & Access](/docs/identity): [users, groups and policies](/docs/identity/users-groups-policies), [MFA and passwords](/docs/identity/mfa-password-policy), [access keys](/docs/identity/access-keys), [roles](/docs/identity/roles-and-sts), [security tools](/docs/identity/security-tools-best-practices); [Console, CLI and SDK](/docs/foundations/console-cli-sdk) 3. **Amazon EC2 – Basics** (slides 41–77) → [Compute](/docs/compute): [EC2 basics](/docs/compute/ec2-basics), [instance types](/docs/compute/instance-types), [security groups](/docs/compute/security-groups), [connecting](/docs/compute/connecting-to-ec2), [purchasing options](/docs/compute/purchasing-options), [Spot Instances](/docs/compute/spot-instances) 4. **Amazon EC2 – Associate** (slides 78–93) → [Compute](/docs/compute): [IP addressing](/docs/compute/ip-addressing), [placement groups](/docs/compute/placement-groups), [ENI](/docs/compute/eni), [hibernate](/docs/compute/hibernate) 5. **Amazon EC2 – Instance Storage** (slides 94–118) → [Storage: Block & File](/docs/storage): [EBS volumes](/docs/storage/ebs-volumes), [snapshots](/docs/storage/ebs-snapshots), [volume types](/docs/storage/ebs-volume-types), [Multi-Attach](/docs/storage/ebs-multi-attach), [encryption](/docs/storage/ebs-encryption), [instance store](/docs/storage/instance-store), [EFS](/docs/storage/efs), [EBS vs EFS vs instance store](/docs/storage/ebs-vs-efs-vs-instance-store); [AMIs](/docs/compute/ami) 6. **High Availability & Scalability** (slides 119–160) → [Load Balancing & Auto Scaling](/docs/scaling): [overview](/docs/scaling), [Elastic Load Balancing](/docs/scaling/elb-overview), [ALB](/docs/scaling/alb), [NLB](/docs/scaling/nlb), [GWLB](/docs/scaling/gwlb), [sticky sessions and cross-zone](/docs/scaling/sticky-sessions-cross-zone), [SSL/TLS and SNI](/docs/scaling/ssl-tls-sni), [Auto Scaling groups](/docs/scaling/auto-scaling-groups), [scaling policies](/docs/scaling/scaling-policies) 7. **RDS, Aurora & ElastiCache** (slides 161–193) → [Databases](/docs/databases): [RDS](/docs/databases/rds), [read replicas and Multi-AZ](/docs/databases/rds-read-replicas-multi-az), [Aurora](/docs/databases/aurora), [Aurora advanced](/docs/databases/aurora-advanced), [backups and cloning](/docs/databases/backups-restore-cloning), [security and RDS Proxy](/docs/databases/rds-security-proxy), [ElastiCache](/docs/databases/elasticache) 8. **Amazon Route 53** (slides 194–227) → [DNS & Content Delivery](/docs/edge): [DNS basics](/docs/edge/dns-basics), [records and hosted zones](/docs/edge/route53-records-zones), [CNAME vs alias](/docs/edge/route53-alias), [routing policies](/docs/edge/route53-routing-policies), [health checks](/docs/edge/route53-health-checks), [registrar and hybrid DNS](/docs/edge/route53-registrar-hybrid-dns) 9. **Classic Solutions Architecture** (slides 228–267) → Architecture Patterns: the three web apps ([stateless](/docs/architecture/stateless-web-app), [stateful](/docs/architecture/stateful-web-app), [WordPress](/docs/architecture/wordpress)); [Elastic Beanstalk](/docs/compute/elastic-beanstalk) 10. **Amazon S3** (slides 268–293) → [Amazon S3](/docs/s3): [overview](/docs/s3), [security and bucket policies](/docs/s3/security-bucket-policies), [static website](/docs/s3/static-website), [versioning and replication](/docs/s3/versioning-replication), [storage classes](/docs/s3/storage-classes) 11. **Amazon S3 – Advanced** (slides 294–313) → [Amazon S3](/docs/s3): [lifecycle rules](/docs/s3/lifecycle-rules), [Requester Pays](/docs/s3/requester-pays), [event notifications](/docs/s3/event-notifications), [performance](/docs/s3/performance), [Batch Operations and Storage Lens](/docs/s3/batch-operations-storage-lens) 12. **Amazon S3 – Security** (slides 314–336) → [Amazon S3](/docs/s3): [encryption](/docs/s3/encryption), [CORS](/docs/s3/cors), [MFA Delete and access logs](/docs/s3/mfa-delete-access-logs), [presigned URLs](/docs/s3/presigned-urls), [Object Lock](/docs/s3/object-lock-vault-lock), [Access Points and Object Lambda](/docs/s3/access-points-object-lambda) 13. **CloudFront & Global Accelerator** (slides 337–351) → [DNS & Content Delivery](/docs/edge): [CloudFront](/docs/edge/cloudfront), [Global Accelerator](/docs/edge/global-accelerator) 14. **AWS Storage Extras** (slides 352–376) → [Migration & Transfer](/docs/migration) ([Snowball](/docs/migration/snow-family), [Storage Gateway](/docs/migration/storage-gateway), [Transfer Family](/docs/migration/transfer-family), [DataSync](/docs/migration/datasync)); [FSx](/docs/storage/fsx), [storage comparison](/docs/storage/storage-comparison) 15. **AWS Integration & Messaging** (slides 377–415) → [Application Integration](/docs/integration): [SQS](/docs/integration/sqs), [FIFO and patterns](/docs/integration/sqs-fifo-patterns), [SNS](/docs/integration/sns), [fan-out](/docs/integration/sns-fan-out), [Kinesis and Firehose](/docs/integration/kinesis), [SQS vs SNS vs Kinesis](/docs/integration/sqs-sns-kinesis), [Amazon MQ](/docs/integration/amazon-mq) 16. **Containers on AWS** (slides 416–440) → [Containers](/docs/containers): [overview](/docs/containers), [ECS](/docs/containers/ecs), [ECS scaling and patterns](/docs/containers/ecs-scaling-patterns), [ECR](/docs/containers/ecr), [EKS](/docs/containers/eks) 17. **Serverless Overview** (slides 441–493) → [Serverless](/docs/serverless): [overview](/docs/serverless), [Lambda](/docs/serverless/lambda), [limits and concurrency](/docs/serverless/lambda-limits-concurrency), [networking](/docs/serverless/lambda-networking), [API Gateway](/docs/serverless/api-gateway); [DNS & Content Delivery](/docs/edge): [edge functions](/docs/edge/edge-functions); [Databases](/docs/databases): [DynamoDB](/docs/databases/dynamodb), [DynamoDB advanced](/docs/databases/dynamodb-advanced); [Application Integration](/docs/integration): [Step Functions](/docs/integration/step-functions); [Amazon Cognito](/docs/identity/cognito) 18. **Serverless Architectures** (slides 494–515) → Architecture Patterns: [MyTodoList](/docs/architecture/serverless-mobile-app), [MyBlog](/docs/architecture/serverless-website), [microservices](/docs/architecture/microservices) 19. **Databases in AWS** (slides 516–529) → [Databases](/docs/databases): [choosing a database](/docs/databases), [DocumentDB, Neptune and Keyspaces](/docs/databases/documentdb-neptune-keyspaces), [Timestream](/docs/databases/timestream) 20. **Data & Analytics** (slides 530–562) → [Analytics](/docs/analytics): [Athena](/docs/analytics/athena), [Redshift](/docs/analytics/redshift), [OpenSearch](/docs/analytics/opensearch), [EMR](/docs/analytics/emr), [QuickSight](/docs/analytics/quicksight), [Glue](/docs/analytics/glue), [Lake Formation](/docs/analytics/lake-formation), [Managed Flink and MSK](/docs/analytics/flink-msk), [big data pipeline](/docs/analytics/big-data-pipeline) 21. **Machine Learning** (slides 563–577) → [Machine Learning](/docs/ml): [summary](/docs/ml), [Rekognition and Textract](/docs/ml/vision-documents), [Transcribe, Polly, Translate, Comprehend](/docs/ml/speech-language), [Lex, Connect, Kendra](/docs/ml/lex-connect-kendra), [SageMaker AI and Personalize](/docs/ml/sagemaker-personalize) 22. **AWS Monitoring, Audit & Performance** (slides 578–621) → [Monitoring & Governance](/docs/management): [CloudWatch metrics](/docs/management/cloudwatch-metrics), [CloudWatch Logs](/docs/management/cloudwatch-logs), [alarms](/docs/management/cloudwatch-alarms), [Insights](/docs/management/cloudwatch-insights), [CloudTrail](/docs/management/cloudtrail), [Config](/docs/management/config); [Application Integration](/docs/integration): [EventBridge](/docs/integration/eventbridge) 23. **Advanced Identity in AWS** (slides 622–650) → [Identity & Access](/docs/identity): [Organizations and SCPs](/docs/identity/organizations-scps), [conditions and evaluation](/docs/identity/policy-conditions-evaluation), [roles vs resource policies](/docs/identity/roles-vs-resource-policies), [IAM Identity Center](/docs/identity/iam-identity-center), [Directory Service](/docs/identity/directory-service), [Control Tower](/docs/identity/control-tower) 24. **AWS Security & Encryption** (slides 651–699) → [Security & Encryption](/docs/security): [encryption](/docs/security), [KMS](/docs/security/kms), [multi-Region keys](/docs/security/kms-multi-region), [Parameter Store](/docs/security/ssm-parameter-store), [Secrets Manager](/docs/security/secrets-manager), [ACM](/docs/security/acm), [CloudHSM](/docs/security/cloudhsm), [WAF, Shield, Firewall Manager](/docs/security/waf-shield-firewall-manager), [DDoS best practices](/docs/security/ddos-best-practices), [GuardDuty, Inspector, Macie](/docs/security/guardduty-inspector-macie) 25. **Amazon VPC** (slides 700–777) → [Networking: Amazon VPC](/docs/vpc): [CIDR](/docs/vpc/cidr-ip-addressing), [VPC and subnets](/docs/vpc/vpc-and-subnets), [IGW and route tables](/docs/vpc/internet-gateway-route-tables), [bastion](/docs/vpc/bastion-hosts), [NAT](/docs/vpc/nat-instance-nat-gateway), [NACLs](/docs/vpc/nacl-vs-security-groups), [peering](/docs/vpc/vpc-peering), [endpoints](/docs/vpc/vpc-endpoints-privatelink), [Flow Logs](/docs/vpc/flow-logs-traffic-mirroring), [VPN](/docs/vpc/site-to-site-vpn), [Direct Connect](/docs/vpc/direct-connect), [Transit Gateway](/docs/vpc/transit-gateway), [IPv6](/docs/vpc/ipv6), [costs](/docs/vpc/networking-costs), [Network Firewall](/docs/vpc/network-firewall) 26. **Disaster Recovery & Migrations** (slides 778–804) → [Disaster Recovery & Backup](/docs/dr) ([RPO and RTO](/docs/dr#rpo-and-rto), [strategies](/docs/dr/dr-strategies), [Elastic Disaster Recovery](/docs/dr/elastic-disaster-recovery), [AWS Backup](/docs/dr/aws-backup)); [Migration & Transfer](/docs/migration) ([DMS and SCT](/docs/migration/dms-sct), [Discovery and MGN](/docs/migration/application-discovery-mgn), [large transfers](/docs/migration/large-data-transfer)) 27. **More Solutions Architecture** (slides 805–826) → Architecture Patterns: [event processing](/docs/architecture/event-processing) to [HA EC2](/docs/architecture/highly-available-ec2) 28. **Other Services** (slides 827–854) → [Monitoring & Governance](/docs/management) ([CloudFormation](/docs/management/cloudformation), [Systems Manager](/docs/management/systems-manager)); [Cost Management](/docs/cost) ([Cost Explorer and Anomaly Detection](/docs/cost/cost-explorer-anomaly), [Instance Scheduler](/docs/cost/instance-scheduler)); Compute ([Batch](/docs/compute/batch), [Outposts](/docs/compute/hybrid-edge-compute)); [Application Integration](/docs/integration) ([SES and Pinpoint](/docs/integration/ses-pinpoint), [AppFlow](/docs/integration/appflow)); [Serverless](/docs/serverless) ([Amplify](/docs/serverless/amplify)) 29. **White Papers & Architectures** (slides 855–861) → Architecture Patterns: [Well-Architected](/docs/architecture/well-architected) 30. **Exam Preparation** (slides 862–877) → [Exam Prep](/docs/exam-prep): exam tips, the [keyword cheat sheet](/docs/exam-prep/keyword-cheatsheet), [certification paths](/docs/exam-prep/certification-paths) ## Topics outside the course [#topics-outside-the-course] The exam guide lists some topics the course skips. They're in the notes too: see [What the course doesn't cover](/docs/exam-guide#what-the-course-doesnt-cover). Read them once you've finished the group they belong to. # Bastion hosts (/docs/vpc/bastion-hosts) ## What it is [#what-it-is]
![A bastion host: users SSH from the corporate network to a bastion EC2 instance in the public subnet, whose security group allows port 22 only from the corporate CIDR; from there they SSH to instances in the private subnet, whose security group allows port 22 from the bastion's security group](/diagrams/vpc-bastion.light.svg) ![A bastion host: users SSH from the corporate network to a bastion EC2 instance in the public subnet, whose security group allows port 22 only from the corporate CIDR; from there they SSH to instances in the private subnet, whose security group allows port 22 from the bastion's security group](/diagrams/vpc-bastion.dark.svg)
A single, locked-down entry point.
- We can use a **[bastion host](/docs/glossary#term-bastion-host)** to **SSH into our private EC2 instances**. - The bastion is in the **public subnet**, which is then connected to all other private subnets. - **The bastion host security group must allow inbound from the internet on port 22 from a restricted CIDR**, for example the **public CIDR of your corporation**. - **The security group of the EC2 instances must allow the security group of the bastion host**, or the **private IP** of the bastion host. Today, AWS offers ways to reach private instances **without a bastion**: **[Session Manager](/docs/management/systems-manager#session-manager)** (no open ports, no SSH keys) and the **[EC2 Instance Connect Endpoint](/docs/compute/connecting-to-ec2#ec2-instance-connect-endpoint)** (SSH to private IPs with no public IP or bastion). For "least operational overhead" or "no inbound ports", pick these. Bastions still appear in exam questions. ## Exam tips [#exam-tips] - **"SSH to instances in a private subnet"** → bastion host in a public subnet (or Session Manager / EIC Endpoint). - **Bastion SG** → port 22 from the **company's public CIDR** only. **Private instance SG** → port 22 from the **bastion's security group**. ## Common traps [#common-traps] - **"Open port 22 on the bastion to 0.0.0.0/0."** Restrict it to known CIDRs. - **"Put the bastion in a private subnet."** It must be reachable, so it's in a public subnet. ## Check yourself [#check-yourself] The lab would need two instances and a key pair, so instead: Bastion SG: inbound TCP 22 from 203.0.113.0/24. App server SG: inbound TCP 22 from the bastion's security group. (Or replace both with Session Manager.) ## AWS documentation [#aws-documentation] - [Linux bastion hosts on AWS](https://aws.amazon.com/solutions/implementations/linux-bastion/) - [Connect using EC2 Instance Connect Endpoint](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-using-eice.html) # CIDR and IP addressing (/docs/vpc/cidr-ip-addressing) ## What CIDR is [#what-cidr-is] **[CIDR](/docs/glossary#term-cidr)** (Classless Inter-Domain Routing) is a method for allocating IP addresses. - Used in **security group rules** and AWS networking in general (for example `0.0.0.0/0` for "anywhere", or `122.149.196.85/32` for one IP). - It defines an **IP address range**: - `WW.XX.YY.ZZ/32` → one IP; - `0.0.0.0/0` → all IPs; - `192.168.0.0/26` → `192.168.0.0` to `192.168.0.63` (64 IP addresses). A CIDR has two parts: - **Base IP:** an IP contained in the range, such as `10.0.0.0` or `192.168.0.0`. - **Subnet mask:** defines **how many bits can change** in the IP. It takes two forms: - `/8` ⇔ `255.0.0.0`; - `/16` ⇔ `255.255.0.0`; - `/24` ⇔ `255.255.255.0`; - `/32` ⇔ `255.255.255.255`. ## Subnet masks [#subnet-masks]
![CIDR subnet masks: /32 is one IP address, /24 is 256 addresses where the last octet changes, /16 is 65,536 addresses where the last two octets change, /8 is about 16.7 million addresses, and /0 is all IP addresses](/diagrams/vpc-cidr-masks.light.svg) ![CIDR subnet masks: /32 is one IP address, /24 is 256 addresses where the last octet changes, /16 is 65,536 addresses where the last two octets change, /8 is about 16.7 million addresses, and /0 is all IP addresses](/diagrams/vpc-cidr-masks.dark.svg)
Each step down the mask doubles the addresses.
The mask says how many of the 32 bits are fixed. The rest can change: a `/n` holds **2^(32 − n)** addresses. - `/32` → 2⁰ = 1 IP (`192.168.0.0`); - `/31` → 2 IPs; `/30` → 4 IPs; `/29` → 8 IPs; `/28` → 16 IPs; - `/27` → 32 IPs; `/26` → 64 IPs; `/25` → 128 IPs; - `/24` → 256 IPs (`192.168.0.0` → `192.168.0.255`); - `/16` → 65,536 IPs (`192.168.0.0` → `192.168.255.255`); - `/0` → all IPs. **Quick memo** (octets are the four numbers of an IP): - `/32`: no octet can change; - `/24`: the last octet can change; - `/16`: the last 2 octets can change; - `/8`: the last 3 octets can change; - `/0`: all octets can change. ## Little exercise [#little-exercise] - `192.168.0.0/24` → `192.168.0.0` to `192.168.0.255` (256 IPs). - `192.168.0.0/16` → `192.168.0.0` to `192.168.255.255` (65,536 IPs). - `134.56.78.123/32` → just `134.56.78.123`. - `0.0.0.0/0` → all IPs. When in doubt, use a CIDR calculator website. ## Private vs public IPv4 [#private-vs-public-ipv4] The **IANA** (Internet Assigned Numbers Authority) reserved certain blocks of IPv4 addresses for **private** networks (LANs). **Private IPs** can only use these values: - `10.0.0.0` – `10.255.255.255` (`10.0.0.0/8`): in big networks; - `172.16.0.0` – `172.31.255.255` (`172.16.0.0/12`): the **AWS default VPC** uses `172.31.0.0/16` from this range; - `192.168.0.0` – `192.168.255.255` (`192.168.0.0/16`): for example, home networks. **All the rest of the IP addresses on the internet are public.** See also [IP addresses on EC2](/docs/compute/ip-addressing). ## Exam tips [#exam-tips] - **"How many IPs in a /24?"** → 256 (minus the 5 AWS reserves in a subnet). - **"Allow one IP in a security group"** → `/32`. **"Allow everyone"** → `0.0.0.0/0`. - **"Private IP ranges"** → `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`. ## Common traps [#common-traps] - **"A bigger mask number means more addresses."** It's the opposite: `/16` is much bigger than `/24`. ## Check yourself [#check-yourself] 2^(32 − 22) = 1,024 addresses: `10.0.4.0` to `10.0.7.255`. ## AWS documentation [#aws-documentation] - [IP addressing for your VPCs and subnets](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-ip-addressing.html) - [VPC CIDR blocks](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-cidr-blocks.html) # AWS Direct Connect (/docs/vpc/direct-connect) ## What it is [#what-it-is]
![AWS Direct Connect: a dedicated line runs from your data center's router to a customer or partner router at a Direct Connect location, cross-connected to the AWS router there; a private virtual interface reaches the VPC through a virtual private gateway, and a public virtual interface reaches public services such as S3 and Glacier](/diagrams/vpc-direct-connect.light.svg) ![AWS Direct Connect: a dedicated line runs from your data center's router to a customer or partner router at a Direct Connect location, cross-connected to the AWS router there; a private virtual interface reaches the VPC through a virtual private gateway, and a public virtual interface reaches public services such as S3 and Glacier](/diagrams/vpc-direct-connect.dark.svg)
A private line from your data center to AWS.
**[AWS Direct Connect](/docs/glossary#term-aws-direct-connect)** (DX) provides a **dedicated private connection** from a remote network to your VPC. - A dedicated connection must be set up between your DC and **AWS Direct Connect locations**. - You need to set up a **virtual private gateway** on your VPC (or a Direct Connect gateway / transit gateway). - Access **public resources (S3)** and **private resources (EC2)** on the same connection, with **virtual interfaces (VIFs)**: - **private VIF:** to a VPC; - **public VIF:** to public AWS services such as S3, in all Regions; - **transit VIF:** to a transit gateway. - **Use cases:** - increase bandwidth throughput: working with large data sets, at lower cost; - a more consistent network experience: applications using real-time data feeds; - hybrid environments (on premises + cloud). - Supports both **IPv4 and IPv6**. ## Direct Connect gateway [#direct-connect-gateway]
![A Direct Connect gateway: one Direct Connect connection from your data center reaches a Direct Connect gateway, a global resource, which connects through private virtual interfaces to VPCs in us-east-1 and us-west-2, and can include VPCs in other accounts](/diagrams/vpc-dx-gateway.light.svg) ![A Direct Connect gateway: one Direct Connect connection from your data center reaches a Direct Connect gateway, a global resource, which connects through private virtual interfaces to VPCs in us-east-1 and us-west-2, and can include VPCs in other accounts](/diagrams/vpc-dx-gateway.dark.svg)
One connection, VPCs in many Regions.
If you want to set up a Direct Connect to **one or more VPCs in many different Regions**, use a **[Direct Connect gateway](/docs/glossary#term-direct-connect-gateway)**. It's a **global** resource, associated with virtual private gateways or transit gateways. The slides say the VPCs must be in the **same account**. A Direct Connect gateway can now be associated with virtual private gateways and transit gateways in **other accounts** too (the other account proposes the association and the gateway owner accepts it). ## Connection types [#connection-types] - **Dedicated connections:** **1, 10, 100 or 400 Gbps** capacity. - A physical Ethernet port dedicated to a customer. - Request made to AWS first, then completed by AWS Direct Connect Partners. - **Hosted connections:** **50 Mbps to 25 Gbps**. - Connection requests are made through **AWS Direct Connect Partners**. - Capacity can be **added or removed on demand**. - **Lead times are often longer than 1 month** to establish a new connection. ## Encryption [#encryption] - Data in transit is **not encrypted**, but it's **private**. - **AWS Direct Connect + VPN** provides an **IPsec-encrypted private connection**. - Good for an extra level of security, but slightly more complex to put in place. Direct Connect also supports **MACsec** (IEEE 802.1AE) on dedicated **10, 100 and 400 Gbps** connections at selected locations: layer 2 encryption between your router and the Direct Connect device, without the VPN overhead. ## Resiliency [#resiliency]
![Direct Connect resiliency: for high resiliency, one connection at each of two Direct Connect locations; for maximum resiliency, separate connections terminating on separate devices at two or more locations](/diagrams/vpc-dx-resiliency.light.svg) ![Direct Connect resiliency: for high resiliency, one connection at each of two Direct Connect locations; for maximum resiliency, separate connections terminating on separate devices at two or more locations](/diagrams/vpc-dx-resiliency.dark.svg)
More locations and devices, more resilience.
- **High resiliency for critical workloads:** one connection at **multiple locations**. - **Maximum resiliency for critical workloads:** achieved by **separate connections terminating on separate devices in more than one location**. ### Site-to-Site VPN as a backup [#site-to-site-vpn-as-a-backup]
![Site-to-Site VPN as a Direct Connect backup: the corporate data center reaches the VPC through Direct Connect as the primary connection, and a cheaper Site-to-Site VPN over the internet takes over if Direct Connect fails](/diagrams/vpc-dx-vpn-backup.light.svg) ![Site-to-Site VPN as a Direct Connect backup: the corporate data center reaches the VPC through Direct Connect as the primary connection, and a cheaper Site-to-Site VPN over the internet takes over if Direct Connect fails](/diagrams/vpc-dx-vpn-backup.dark.svg)
A cheap safety net for the private line.
In case Direct Connect fails, you can set up a **backup Direct Connect connection** (expensive), or a **Site-to-Site VPN connection**. ## Real-world examples [#real-world-examples] - **A bank** moves 50 TB of nightly batch data between its data center and AWS. A 10 Gbps Direct Connect gives steady throughput and lower data transfer prices than the internet; a Site-to-Site VPN is the backup. ## Exam tips [#exam-tips] - **"Dedicated, private, consistent network performance to AWS", "large data, low latency"** → Direct Connect. - **"Need connectivity next week"** → Site-to-Site VPN (Direct Connect takes over a month). - **"Encrypt traffic over Direct Connect"** → VPN over Direct Connect (IPsec), or MACsec. - **"Direct Connect to VPCs in several Regions"** → Direct Connect gateway. - **"Cheapest backup for Direct Connect"** → Site-to-Site VPN. - **"Maximum resiliency"** → separate connections on separate devices at more than one location. - **"Less than 1 Gbps, from a partner"** → hosted connection. ## Common traps [#common-traps] - **"Direct Connect is encrypted."** It's private, not encrypted. - **"Direct Connect can be ready in days."** Lead time is often over a month. ## Check yourself [#check-yourself] Direct Connect needs a physical circuit, so instead: Direct Connect with a Direct Connect gateway associated with both VPCs' gateways, and an IPsec VPN over the Direct Connect connection (or MACsec on a supported dedicated connection) for encryption. ## AWS documentation [#aws-documentation] - [What is Direct Connect?](https://docs.aws.amazon.com/directconnect/latest/UserGuide/Welcome.html) - [Dedicated and hosted connections](https://docs.aws.amazon.com/directconnect/latest/UserGuide/WorkingWithConnections.html) - [Direct Connect gateways](https://docs.aws.amazon.com/directconnect/latest/UserGuide/direct-connect-gateways-intro.html) - [MACsec in Direct Connect](https://docs.aws.amazon.com/directconnect/latest/UserGuide/MACsec.html) - [Direct Connect resiliency recommendations](https://aws.amazon.com/directconnect/resiliency-recommendation/) # VPC Flow Logs and Traffic Mirroring (/docs/vpc/flow-logs-traffic-mirroring) ## VPC Flow Logs [#vpc-flow-logs] **[VPC Flow Logs](/docs/glossary#term-vpc-flow-logs)** capture information about **IP traffic** going into your interfaces: - **VPC** flow logs; - **subnet** flow logs; - **elastic network interface (ENI)** flow logs. They help to **monitor and troubleshoot connectivity issues**. - Flow log data can go to **S3**, **CloudWatch Logs** and **Data Firehose**. - They capture network information from **AWS managed interfaces** too: ELB, RDS, ElastiCache, Redshift, WorkSpaces, NAT gateway, Transit Gateway… - They record **metadata** (who talked to whom, on which port, accepted or rejected), **not the packet contents**. ### Flow log syntax [#flow-log-syntax] ```text 2 123456789010 eni-1235b8ca123456789 172.31.16.139 172.31.16.21 20641 22 6 20 4249 1418530010 1418530070 ACCEPT OK 2 123456789010 eni-1235b8ca123456789 172.31.9.69 172.31.9.12 49761 3389 6 20 4249 1418530010 1418530070 REJECT OK ``` The fields: `version`, `account-id`, `interface-id`, `srcaddr`, `dstaddr`, `srcport`, `dstport`, `protocol`, `packets`, `bytes`, `start`, `end`, `action`, `log-status`. - **srcaddr and dstaddr:** help identify problematic IPs. - **srcport and dstport:** help identify problematic ports. - **action:** success or failure of the request because of a **security group or NACL**. - Can be used for analytics on usage patterns, or malicious behaviour. - **Query VPC Flow Logs** with **Athena** on S3, or **CloudWatch Logs Insights**. ### Troubleshooting security groups and NACLs [#troubleshooting-security-groups-and-nacls] Look at the **action** field: - **Incoming requests:** - inbound **REJECT** → NACL or SG; - inbound **ACCEPT**, outbound **REJECT** → **NACL** (a security group would have allowed the response, because it's stateful). - **Outgoing requests:** - outbound **REJECT** → NACL or SG; - outbound **ACCEPT**, inbound **REJECT** → **NACL**. ### Architectures [#architectures]
![Three ways to use VPC Flow Logs: send them to CloudWatch Logs and use Contributor Insights to find the top-10 IP addresses; send them to CloudWatch Logs with a metric filter and alarm that alerts SNS, for example on SSH or RDP traffic; or store them in S3, query them with Athena and visualize them in QuickSight](/diagrams/vpc-flow-logs-arch.light.svg) ![Three ways to use VPC Flow Logs: send them to CloudWatch Logs and use Contributor Insights to find the top-10 IP addresses; send them to CloudWatch Logs with a metric filter and alarm that alerts SNS, for example on SSH or RDP traffic; or store them in S3, query them with Athena and visualize them in QuickSight](/diagrams/vpc-flow-logs-arch.dark.svg)
Find top talkers, alert on bad traffic, or analyse at scale.
- **CloudWatch Logs → [Contributor Insights](/docs/management/cloudwatch-insights#contributor-insights)** → the top-10 IP addresses. - **CloudWatch Logs → [metric filter](/docs/management/cloudwatch-alarms#good-to-know)** (SSH, RDP…) → CloudWatch alarm → SNS alert. - **S3 bucket → Athena → QuickSight** for analysis and dashboards. **CloudWatch permissions:** the **IAM service role** used by VPC Flow Logs must have permission to publish to CloudWatch Logs: `logs:CreateLogGroup`, `logs:CreateLogStream`, `logs:PutLogEvents` (and `DescribeLogGroups`, `DescribeLogStreams`). ## Traffic Mirroring [#traffic-mirroring]
![VPC Traffic Mirroring: inbound and outbound traffic of source ENIs A and B is copied, optionally filtered and truncated, to a target, a Network Load Balancer, a Gateway Load Balancer or a single ENI, in front of a fleet of security appliances that inspect it](/diagrams/vpc-traffic-mirroring.light.svg) ![VPC Traffic Mirroring: inbound and outbound traffic of source ENIs A and B is copied, optionally filtered and truncated, to a target, a Network Load Balancer, a Gateway Load Balancer or a single ENI, in front of a fleet of security appliances that inspect it](/diagrams/vpc-traffic-mirroring.dark.svg)
A copy of the real packets, for deep inspection.
**[Traffic Mirroring](/docs/glossary#term-traffic-mirroring)** lets you **capture and inspect network traffic** in your VPC. - Routes the traffic to **security appliances that you manage**. - **Capture the traffic:** - **from (source):** ENIs; - **to (target):** an ENI, a **Network Load Balancer**, or a **Gateway Load Balancer** (with a UDP listener). - Capture **all packets**, or only the packets of interest (filters), and optionally **truncate** packets. - Source and target can be in the **same VPC or different VPCs** (VPC peering). - **Use cases:** content inspection, threat monitoring, troubleshooting… Flow Logs give **metadata**; Traffic Mirroring gives a **copy of the packets**. ## Exam tips [#exam-tips] - **"Troubleshoot why connections are rejected"**, **"which IPs talk to my instance"** → VPC Flow Logs. - **"Inbound ACCEPT but outbound REJECT"** → NACL (stateless) problem. - **"Analyse flow logs with SQL"** → S3 + Athena (or CloudWatch Logs Insights). - **"Inspect packet contents with an IDS appliance"** → Traffic Mirroring. ## Common traps [#common-traps] - **"Flow Logs show the packet payload."** Only metadata; for packets, use Traffic Mirroring. - **"Flow Logs to CloudWatch work without permissions."** They need an IAM role that can write logs. ## Check yourself [#check-yourself] Flow logs to S3 cost little, but need traffic to be meaningful, so instead: The NACL: it allows inbound port 22 but its outbound rules don't allow the ephemeral port range back to the client. The security group would have allowed the response automatically. ## AWS documentation [#aws-documentation] - [Logging IP traffic using VPC Flow Logs](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html) - [Flow log records](https://docs.aws.amazon.com/vpc/latest/userguide/flow-log-records.html) - [What is Traffic Mirroring?](https://docs.aws.amazon.com/vpc/latest/mirroring/what-is-traffic-mirroring.html) # Networking: Amazon VPC (/docs/vpc) ## The VPC components map [#the-vpc-components-map] An **[Amazon VPC](/docs/glossary#term-amazon-vpc)** (Virtual Private Cloud) is your own private network in an AWS Region. Almost everything else in AWS (EC2, RDS, Lambda in a VPC, load balancers) lives inside one.
![Amazon VPC components: in a Region, a VPC has a public subnet with a NAT gateway and web servers reached through the internet gateway, and a private subnet with app servers and a VPC endpoint; the VPC connects to other networks through VPC peering, Transit Gateway, Site-to-Site VPN and Direct Connect](/diagrams/vpc-components.light.svg) ![Amazon VPC components: in a Region, a VPC has a public subnet with a NAT gateway and web servers reached through the internet gateway, and a private subnet with app servers and a VPC endpoint; the VPC connects to other networks through VPC peering, Transit Gateway, Site-to-Site VPN and Direct Connect](/diagrams/vpc-components.dark.svg)
Everything in this group on one map.
## Section summary [#section-summary] - **[CIDR](/docs/vpc/cidr-ip-addressing):** an IP range. - **[VPC](/docs/vpc/vpc-and-subnets):** Virtual Private Cloud; we define a list of IPv4 and IPv6 CIDRs. - **[Subnets](/docs/vpc/vpc-and-subnets#subnets):** tied to an AZ; we define a CIDR. - **[Internet gateway](/docs/vpc/internet-gateway-route-tables):** at the VPC level, provides IPv4 and IPv6 internet access. - **[Route tables](/docs/vpc/internet-gateway-route-tables#route-tables):** must be edited to add routes from subnets to the IGW, VPC peering connections, VPC endpoints… - **[Bastion host](/docs/vpc/bastion-hosts):** a public EC2 instance to SSH into, which has SSH access to EC2 instances in private subnets. - **[NAT instance](/docs/vpc/nat-instance-nat-gateway#nat-instance):** gives internet access to EC2 instances in private subnets. Old; must be in a public subnet, with the source/destination check turned off. - **[NAT gateway](/docs/vpc/nat-instance-nat-gateway#nat-gateway):** managed by AWS; scalable internet access for private EC2 instances, for IPv4 targets. - **[NACL](/docs/vpc/nacl-vs-security-groups):** stateless subnet rules for inbound and outbound; don't forget ephemeral ports. - **[Security groups](/docs/compute/security-groups):** stateful, at the EC2 instance level. - **[VPC peering](/docs/vpc/vpc-peering):** connect two VPCs with non-overlapping CIDRs; not transitive. - **[VPC endpoints](/docs/vpc/vpc-endpoints-privatelink):** private access to AWS services (S3, DynamoDB, CloudFormation, SSM…) from within a VPC. - **[VPC Flow Logs](/docs/vpc/flow-logs-traffic-mirroring):** at the VPC, subnet or ENI level, for ACCEPT and REJECT traffic; helps find attacks; analyse with Athena or CloudWatch Logs Insights. - **[Site-to-Site VPN](/docs/vpc/site-to-site-vpn):** a customer gateway in your data center, a virtual private gateway on the VPC, and a VPN over the public internet. - **[VPN CloudHub](/docs/vpc/site-to-site-vpn#aws-vpn-cloudhub):** hub-and-spoke VPN model to connect your sites. - **[Direct Connect](/docs/vpc/direct-connect):** a virtual private gateway on the VPC and a direct private connection to a Direct Connect location. - **[Direct Connect gateway](/docs/vpc/direct-connect#direct-connect-gateway):** Direct Connect to many VPCs in different Regions. - **[AWS PrivateLink / VPC endpoint services](/docs/vpc/vpc-endpoints-privatelink#privatelink-endpoint-services):** connect services privately from your service VPC to customer VPCs, with no peering, public internet, NAT gateway or route tables; needs a Network Load Balancer and ENIs. - **[Transit Gateway](/docs/vpc/transit-gateway):** transitive connections between VPCs, VPN and Direct Connect. - **[Traffic Mirroring](/docs/vpc/flow-logs-traffic-mirroring#traffic-mirroring):** copy network traffic from ENIs for analysis. - **[Egress-only internet gateway](/docs/vpc/ipv6#egress-only-internet-gateway):** like a NAT gateway, but for IPv6. - **[Network Firewall](/docs/vpc/network-firewall):** protects a whole VPC from layer 3 to layer 7. The slides also mention **ClassicLink**, which connected EC2-Classic instances to a VPC. EC2-Classic was retired in 2023, so ClassicLink no longer exists. ## In this group [#in-this-group] ## Exam tips [#exam-tips] - Networking questions are about **picking the right component**: internet access (IGW, NAT), private AWS access (endpoints), VPC to VPC (peering, Transit Gateway), on premises (VPN, Direct Connect), filtering (security groups, NACLs, Network Firewall). ## AWS documentation [#aws-documentation] - [What is Amazon VPC?](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) - [Amazon VPC quotas](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) # Internet gateway and route tables (/docs/vpc/internet-gateway-route-tables) ## Internet gateway (IGW) [#internet-gateway-igw] **An [internet gateway](/docs/glossary#term-internet-gateway)** allows resources (such as EC2 instances) in a VPC to **connect to the internet**. - It **scales horizontally** and is **highly available and redundant**: there's nothing to size. - It must be **created separately** from a VPC. - **One VPC can only be attached to one IGW**, and vice versa. - **Internet gateways on their own don't allow internet access…** **route tables must also be edited.** ## Route tables [#route-tables]
![Internet gateway and route tables: the public subnet's route table sends 10.0.0.0/16 locally and 0.0.0.0/0 to the internet gateway, so its instances reach the internet; the private subnet's route table has only the local route](/diagrams/vpc-igw-route-tables.light.svg) ![Internet gateway and route tables: the public subnet's route table sends 10.0.0.0/16 locally and 0.0.0.0/0 to the internet gateway, so its instances reach the internet; the private subnet's route table has only the local route](/diagrams/vpc-igw-route-tables.dark.svg)
A route to the IGW is what makes a subnet public.
- A **[route table](/docs/glossary#term-route-table)** decides where traffic from a subnet goes. Each subnet is associated with **one** route table (the VPC's **main** route table if you don't choose). - Every route table has the **local route** (the VPC CIDR → `local`), so all subnets in a VPC can reach each other. - **Public subnet:** add `0.0.0.0/0 → igw-…` (and `::/0` for IPv6). - **Private subnet:** no route to the IGW (usually `0.0.0.0/0 → nat-…` for outbound access, see [NAT](/docs/vpc/nat-instance-nat-gateway)). - Instances in the public subnet also need a **public IPv4** (auto-assigned or an Elastic IP) to talk to the internet. - The most specific route wins: `10.0.1.0/24` beats `10.0.0.0/16`. ## Real-world examples [#real-world-examples] - **A web tier** in public subnets with a route to the IGW, and an app tier in private subnets with only the local route and a route to a NAT gateway. ## Exam tips [#exam-tips] - **"Instance in a public subnet can't reach the internet"** → check the route `0.0.0.0/0 → IGW`, a public IP, security groups and NACLs. - **"Make a subnet public"** → route table with `0.0.0.0/0` to an internet gateway. ## Common traps [#common-traps] - **"Attaching an IGW makes every subnet public."** Only subnets whose route table points to it. - **"Attach two IGWs to a VPC."** One per VPC. ## Hands-on lab: make a subnet public [#hands-on-lab-make-a-subnet-public] **Goal:** add an internet gateway and a public route table to the VPC from the [previous lab](/docs/vpc/vpc-and-subnets#hands-on-lab-build-a-vpc-with-subnets). Internet gateways and route tables are free. If you launch a test instance, a `t3.micro` costs about $0.01 an hour plus about $0.005 an hour for its public IPv4 address. Use the same Region as before. ### Create and attach the IGW [#create-and-attach-the-igw] **Internet gateways → Create**: `saa-igw`, then **Actions → Attach to VPC** → `saa-vpc`. ### Create the public route table [#create-the-public-route-table] **Route tables → Create**: `saa-public-rt` in `saa-vpc`. **Edit routes → Add route** `0.0.0.0/0` → `saa-igw`. **Subnet associations** → `saa-public-a`. ### Auto-assign public IPs [#auto-assign-public-ips] Select `saa-public-a` → **Actions → Edit subnet settings** → tick **Enable auto-assign public IPv4 address**. **Expected result:** `saa-public-a` uses `saa-public-rt` with a route to the IGW; `saa-private-a` still uses the main route table with only the local route. **Clean up:** delete the route table, detach and delete the IGW, then delete `saa-vpc`. ## AWS documentation [#aws-documentation] - [Enable internet access using an internet gateway](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) - [Configure route tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html) # IPv6 in a VPC (/docs/vpc/ipv6) ## What is IPv6? [#what-is-ipv6] - **IPv4** was designed to provide **4.3 billion addresses** (they'll be exhausted soon). - **IPv6** is the successor of IPv4. - IPv6 is designed to provide **3.4 × 10³⁸** unique IP addresses. - **Every IPv6 address in AWS is public** and internet-routable (no private range). - **Format:** `x.x.x.x.x.x.x.x` written as 8 groups separated by colons, where each `x` is hexadecimal (`0000` to `ffff`). - Examples: - `2001:db8:3333:4444:5555:6666:7777:8888`; - `2001:db8:3333:4444:cccc:dddd:eeee:ffff`; - `::` → all 8 segments are zero; - `2001:db8::` → the last 6 segments are zero; - `::1234:5678` → the first 6 segments are zero; - `2001:db8::1234:5678` → the middle 4 segments are zero. ## IPv6 in a VPC [#ipv6-in-a-vpc] - **IPv4 can't be disabled for your VPC and subnets** (it's the default addressing). - You can **enable IPv6** (public IP addresses) to operate in **dual-stack mode**. - Your EC2 instances get at least a **private internal IPv4** and a **public IPv6**. - They can communicate using either IPv4 or IPv6 to the internet through an **internet gateway**. You can also create **IPv6-only subnets** (no IPv4 CIDR) in a dual-stack VPC, but the VPC itself always keeps IPv4. ## IPv4 troubleshooting [#ipv4-troubleshooting] - So, if you **can't launch an EC2 instance** in your subnet: - it's **not** because it can't get an IPv6 (the space is very large); - it's because there are **no available IPv4** addresses in your subnet. - **Solution:** add a new IPv4 CIDR to the VPC and create a subnet in it. ## Egress-only internet gateway [#egress-only-internet-gateway]
![IPv6 in a VPC: the web server in the public subnet uses the internet gateway, which carries IPv4 and IPv6 in both directions; the server in the private subnet uses an egress-only internet gateway, which lets it start IPv6 connections to the internet but stops the internet from starting connections to it](/diagrams/vpc-ipv6-egress.light.svg) ![IPv6 in a VPC: the web server in the public subnet uses the internet gateway, which carries IPv4 and IPv6 in both directions; the server in the private subnet uses an egress-only internet gateway, which lets it start IPv6 connections to the internet but stops the internet from starting connections to it](/diagrams/vpc-ipv6-egress.dark.svg)
Outbound IPv6 only, like NAT for IPv4.
An **[egress-only internet gateway](/docs/glossary#term-egress-only-internet-gateway)**: - is **used for IPv6 only** (similar to a NAT gateway, but for IPv6); - allows instances in your VPC **outbound connections over IPv6**, while **preventing the internet from initiating** an IPv6 connection to your instances; - **you must update the route tables.** ## IPv6 routing [#ipv6-routing] **Public subnet route table:** - `10.0.0.0/16` → local; `2001:db8:1234:1a00::/56` → local; - `0.0.0.0/0` → **igw-id**; `::/0` → **igw-id**. **Private subnet route table:** - `10.0.0.0/16` → local; `2001:db8:1234:1a00::/56` → local; - `0.0.0.0/0` → **nat-gateway-id** (IPv4 outbound); - `::/0` → **eigw-id** (IPv6 outbound). ## Exam tips [#exam-tips] - **"Can't launch instances, subnet has IPv6"** → the subnet ran out of **IPv4** addresses; add an IPv4 CIDR. - **"Private instances need outbound-only IPv6"** → egress-only internet gateway. - **"Outbound-only IPv4"** → NAT gateway. ## Common traps [#common-traps] - **"Disable IPv4 in the VPC to use only IPv6."** IPv4 can't be disabled for the VPC. - **"Use a NAT gateway for IPv6 outbound."** Use an egress-only internet gateway. ## Check yourself [#check-yourself] Create an egress-only internet gateway and add `::/0 → eigw-…` to the private subnet's route table. ## AWS documentation [#aws-documentation] - [Add IPv6 support for your VPC](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-migrate-ipv6.html) - [Egress-only internet gateways](https://docs.aws.amazon.com/vpc/latest/userguide/egress-only-internet-gateway.html) # NACLs vs security groups (/docs/vpc/nacl-vs-security-groups) ## How traffic is checked [#how-traffic-is-checked]
![How NACLs and security groups check traffic: for an incoming request, the NACL inbound rules are checked, then the security group inbound rules; the response is allowed by the stateful security group, but the stateless NACL checks its outbound rules again; for an outgoing request, the security group outbound rules are checked, then the NACL outbound rules, and the response passes the security group automatically but must match the NACL inbound rules](/diagrams/vpc-sg-nacl-path.light.svg) ![How NACLs and security groups check traffic: for an incoming request, the NACL inbound rules are checked, then the security group inbound rules; the response is allowed by the stateful security group, but the stateless NACL checks its outbound rules again; for an outgoing request, the security group outbound rules are checked, then the NACL outbound rules, and the response passes the security group automatically but must match the NACL inbound rules](/diagrams/vpc-sg-nacl-path.dark.svg)
The NACL checks both directions; the security group remembers.
## Network ACLs [#network-acls] A **[network ACL](/docs/glossary#term-network-acl)** (NACL) is like a **firewall that controls traffic from and to subnets**. - **One NACL per subnet**; new subnets are assigned the **default NACL**. - You define **NACL rules**: - rules have a **number (1 to 32766)**; a **lower number has higher precedence**; - the **first rule that matches drives the decision**; - example: with `#100 ALLOW 10.0.0.10/32` and `#200 DENY 10.0.0.10/32`, the IP is **allowed**, because 100 comes first; - the last rule is an asterisk (`*`) that **denies** a request when no rule matches; - AWS recommends adding rules in **increments of 100**. - **Newly created custom NACLs deny everything.** - NACLs are a great way to **block a specific IP address** at the subnet level (security groups can't deny). ### Default NACL [#default-nacl] - **Accepts everything** inbound and outbound for the subnets it's associated with (rule `100` ALLOW all, then `*` DENY). - **Do NOT modify the default NACL**; create custom NACLs instead. ## Ephemeral ports [#ephemeral-ports]
![Ephemeral ports: the client 11.22.33.44 connects from a random ephemeral port such as 50105 to port 443 on the web server 55.66.77.88, and the response returns to port 50105; because NACLs are stateless, they must allow the ephemeral port range back, and 1024 to 65535 is the safe choice](/diagrams/vpc-ephemeral-ports.light.svg) ![Ephemeral ports: the client 11.22.33.44 connects from a random ephemeral port such as 50105 to port 443 on the web server 55.66.77.88, and the response returns to port 50105; because NACLs are stateless, they must allow the ephemeral port range back, and 1024 to 65535 is the safe choice](/diagrams/vpc-ephemeral-ports.dark.svg)
Responses come back to a random high port.
- For any two endpoints to establish a connection, they must use **ports**. - Clients connect to a **defined port** (such as 443), and expect a response on an **[ephemeral port](/docs/glossary#term-ephemeral-port)**: a random high port the client OS picks. - Different operating systems use different ranges: - IANA and Windows 10: **49152–65535**; - many Linux kernels: **32768–60999**. **NACL with ephemeral ports:** for a web tier talking to a database on port 3306: - **Web subnet NACL:** allow **outbound** TCP 3306 to the DB subnet CIDR; allow **inbound** TCP **1024–65535** from the DB subnet CIDR (the responses). - **DB subnet NACL:** allow **inbound** TCP 3306 from the web subnet CIDR; allow **outbound** TCP **1024–65535** to the web subnet CIDR. - Create NACL rules **for each target subnet CIDR** (for example, both web subnets in AZ A and AZ B). ## Security group vs NACL [#security-group-vs-nacl] **Security group:** - operates at the **instance level** (ENI); - supports **allow rules only**; - **stateful:** return traffic is automatically allowed, regardless of any rules; - **all rules are evaluated** before deciding; - applies to an EC2 instance when someone specifies it. **NACL:** - operates at the **subnet level**; - supports **allow and deny** rules; - **stateless:** return traffic must be explicitly allowed (think of ephemeral ports); - rules are evaluated **in order (lowest to highest)**; first match wins; - automatically applies to **all instances in the subnets** it's associated with. See also [security groups](/docs/compute/security-groups). ## Real-world examples [#real-world-examples] - **A security team** sees attacks from `198.51.100.23`. Security groups can't deny, so they add NACL rule `#50 DENY 198.51.100.23/32` on the public subnets. ## Exam tips [#exam-tips] - **"Block a specific IP address"** → NACL deny rule (security groups can't deny). - **"Allowed inbound but the response never arrives"** → NACL outbound rules missing the ephemeral port range. - **"Rule order"** → NACLs evaluate lowest number first; security groups evaluate all rules. - **"Stateful vs stateless"** → security groups stateful, NACLs stateless. ## Common traps [#common-traps] - **"A new custom NACL allows all traffic."** It denies everything until you add rules; the default NACL allows all. - **"Deny rules in a security group."** Only allow rules exist. ## Check yourself [#check-yourself] No. Rule #100 matches first and denies all SSH; rule #200 is never evaluated for that traffic. Give the allow rule a lower number than the deny. ## AWS documentation [#aws-documentation] - [Control subnet traffic with network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html) - [Custom network ACLs and ephemeral ports](https://docs.aws.amazon.com/vpc/latest/userguide/custom-network-acl.html) - [Infrastructure security in Amazon VPC](https://docs.aws.amazon.com/vpc/latest/userguide/infrastructure-security.html) # NAT instance and NAT gateway (/docs/vpc/nat-instance-nat-gateway) ## NAT instance [#nat-instance]
![A NAT instance: private instances 10.0.0.10 and 10.0.0.20 route 0.0.0.0/0 to a NAT instance in the public subnet, which has an Elastic IP and source/destination check turned off; it rewrites the source address to its Elastic IP and forwards the traffic to the internet server](/diagrams/vpc-nat-instance.light.svg) ![A NAT instance: private instances 10.0.0.10 and 10.0.0.20 route 0.0.0.0/0 to a NAT instance in the public subnet, which has an Elastic IP and source/destination check turned off; it rewrites the source address to its Elastic IP and forwards the traffic to the internet server](/diagrams/vpc-nat-instance.dark.svg)
Outdated, but still on the exam.
**NAT** = Network Address Translation. A **[NAT instance](/docs/glossary#term-nat-instance)** is an EC2 instance that does it for you. - Allows EC2 instances in **private subnets** to **connect to the internet** (outbound only: the internet can't start connections to them). - Must be launched in a **public subnet**. - Must **disable** the EC2 setting **source / destination check** (it forwards traffic that isn't for itself). - Must have an **Elastic IP** attached to it. - **Route tables** must be configured to route traffic from private subnets to the NAT instance. **Comments:** - A pre-configured Amazon Linux NAT AMI was available, but it reached the **end of standard support on 31 December 2020**. - **Not highly available / resilient** out of the box: you need an ASG in multiple AZs and a resilient user-data script. - Internet traffic **bandwidth depends on the EC2 instance type**. - You must manage **security groups and rules**: - inbound: allow HTTP/HTTPS traffic coming from private subnets; allow SSH from your home network (through the internet gateway); - outbound: allow HTTP/HTTPS traffic to the internet. ## NAT gateway [#nat-gateway] A **[NAT gateway](/docs/glossary#term-nat-gateway)** is **AWS-managed NAT**: higher bandwidth, high availability, no administration. - **Pay per hour** for usage and **per GB** of data processed. - A NAT gateway is created in a **specific Availability Zone** and uses an **Elastic IP**. - It **can't be used by EC2 instances in the same subnet** (only from other subnets). - **Requires an IGW** (private subnet → NAT gateway → IGW). - **5 Gbps** of bandwidth with automatic scaling up to **100 Gbps**. - **No security groups** to manage or required. ### High availability [#high-availability]
![NAT gateways for high availability: each Availability Zone has its own NAT gateway in its public subnet, and each private subnet routes to the NAT gateway in its own AZ, which reaches the internet through the internet gateway; if one AZ fails, the other AZ keeps working](/diagrams/vpc-nat-gateway-ha.light.svg) ![NAT gateways for high availability: each Availability Zone has its own NAT gateway in its public subnet, and each private subnet routes to the NAT gateway in its own AZ, which reaches the internet through the internet gateway; if one AZ fails, the other AZ keeps working](/diagrams/vpc-nat-gateway-ha.dark.svg)
One NAT gateway per AZ.
- A NAT gateway is **resilient within a single Availability Zone**. - You must create **multiple NAT gateways in multiple AZs** for fault tolerance. - There's **no cross-AZ failover** needed: if an AZ goes down, its instances are down too and don't need NAT. ## Regional NAT gateway [#regional-nat-gateway]
![A Regional NAT gateway: one NAT gateway for the VPC expands automatically to every Availability Zone with workloads and has its own route table to the internet gateway; private subnets in AZ A and AZ B route to it without any public subnet](/diagrams/vpc-nat-regional.light.svg) ![A Regional NAT gateway: one NAT gateway for the VPC expands automatically to every Availability Zone with workloads and has its own route table to the internet gateway; private subnets in AZ A and AZ B route to it without any public subnet](/diagrams/vpc-nat-regional.dark.svg)
One NAT gateway that follows your workloads across AZs.
A **Regional NAT gateway** (the slides call it RNAT) is a **highly available NAT gateway associated with the VPC**, instead of one AZ. - It has **its own route table** (to the IGW). - It **removes the need for per-AZ deployments**: one NAT gateway shared across AZs. - You **don't need public subnets** in your VPC to host it. - It **automatically detects resources in a new AZ and expands** to it. - It's charged per hour **for each AZ** it's active in, plus per GB. - Regional NAT gateways are for public internet access only; for **private NAT** (to other VPCs or on premises), use zonal NAT gateways. ## NAT gateway vs NAT instance [#nat-gateway-vs-nat-instance] **NAT gateway:** - availability: highly available within an AZ (create one per AZ, or use a Regional NAT gateway); - bandwidth: up to 100 Gbps; - maintenance: managed by AWS; - cost: per hour and amount of data processed; - **no security groups**; **can't be used as a bastion host**. **NAT instance:** - availability: you script failover between instances; - bandwidth: depends on the EC2 instance type; - maintenance: managed by you (software, OS patches…); - cost: per hour, EC2 instance type and size, plus network; - **security groups** apply; **can be used as a bastion host**. Both support public and private IPv4. ## Real-world examples [#real-world-examples] - **A company** runs app servers in private subnets in three AZs, with a NAT gateway in each AZ so the servers can download OS updates. Later it switches to one Regional NAT gateway and deletes the public NAT subnets. ## Exam tips [#exam-tips] - **"Private instances need outbound internet (patches, APIs), no inbound"** → NAT gateway. - **"Highly available NAT"** → one NAT gateway per AZ, each AZ's private subnets routing to their own (or a Regional NAT gateway). - **"NAT instance not working"** → disable source/destination check, Elastic IP, route table, security groups. - **"Least operational overhead"** → NAT gateway, not NAT instance. - **"IPv6 outbound only"** → egress-only internet gateway, not NAT (see [IPv6](/docs/vpc/ipv6)). ## Common traps [#common-traps] - **"One NAT gateway serves all AZs with no risk."** A zonal NAT gateway fails with its AZ. - **"Attach a security group to the NAT gateway."** It doesn't support security groups. - **"Put the NAT gateway in the private subnet."** A (zonal, public) NAT gateway sits in a public subnet. ## Check yourself [#check-yourself] A NAT gateway costs about $0.045 an hour plus $0.045 per GB, so instead: Create a second NAT gateway in a public subnet in AZ B and route AZ B's private subnets to it (or replace both with a Regional NAT gateway). ## AWS documentation [#aws-documentation] - [NAT gateways](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) - [NAT gateway basics](https://docs.aws.amazon.com/vpc/latest/userguide/nat-gateway-basics.html) - [Regional NAT gateways](https://docs.aws.amazon.com/vpc/latest/userguide/nat-gateways-regional.html) - [Compare NAT gateways and NAT instances](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-comparison.html) - [NAT instances](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_NAT_Instance.html) # AWS Network Firewall (/docs/vpc/network-firewall) ## Network protection on AWS [#network-protection-on-aws] To protect a network on AWS, we've seen: - **network ACLs** ([NACLs](/docs/vpc/nacl-vs-security-groups)); - Amazon VPC **[security groups](/docs/compute/security-groups)**; - **[AWS WAF](/docs/security/waf-shield-firewall-manager#aws-waf)** (protects against malicious HTTP requests); - **AWS Shield** and Shield Advanced; - **AWS Firewall Manager** (to manage them across accounts). But what if we want to protect our **entire VPC** in a sophisticated way? ## AWS Network Firewall [#aws-network-firewall]
![AWS Network Firewall protects the whole VPC from layer 3 to layer 7: it inspects traffic in every direction, to and from the internet, to and from on premises over Direct Connect and Site-to-Site VPN, and to peered VPCs, with stateful rules and intrusion prevention](/diagrams/vpc-network-firewall.light.svg) ![AWS Network Firewall protects the whole VPC from layer 3 to layer 7: it inspects traffic in every direction, to and from the internet, to and from on premises over Direct Connect and Site-to-Site VPN, and to peered VPCs, with stateful rules and intrusion prevention](/diagrams/vpc-network-firewall.dark.svg)
One firewall for every path in and out of the VPC.
**[AWS Network Firewall](/docs/glossary#term-aws-network-firewall)** protects your **entire Amazon VPC**. - From **layer 3 to layer 7** protection. - **Any direction**, you can inspect: - VPC to VPC traffic; - outbound to the internet; - inbound from the internet; - to and from **Direct Connect** and **Site-to-Site VPN**. - Internally, AWS Network Firewall uses the **AWS [Gateway Load Balancer](/docs/scaling/gwlb)**. - Rules can be **centrally managed cross-account** by **AWS Firewall Manager** to apply to many VPCs. ### Fine-grained controls [#fine-grained-controls] - Supports **thousands of rules**: - **IP and port:** for example, filtering tens of thousands of IPs; - **protocol:** for example, block the SMB protocol for outbound communications; - **stateful domain list rule groups:** only allow outbound traffic to `*.mycorp.com` or a third-party software repository; - general **pattern matching** using regex (it uses Suricata-compatible rules). - **Traffic filtering:** **allow, drop or alert** for the traffic that matches the rules. - **Active flow inspection** to protect against network threats with **intrusion-prevention** capabilities (like Gateway Load Balancer, but all managed by AWS). - Send **logs of rule matches** to **S3**, **CloudWatch Logs** and **Data Firehose**. ## Exam tips [#exam-tips] - **"Protect the entire VPC", "filter outbound traffic by domain name", "intrusion prevention (IPS) for a VPC"** → AWS Network Firewall. - **"Block malicious HTTP requests to an ALB"** → AWS WAF instead. - **"Same firewall rules across many accounts"** → Firewall Manager with Network Firewall policies. ## Common traps [#common-traps] - **"Security groups can filter by domain name."** They filter by IP, port and protocol; domain filtering needs Network Firewall. ## Check yourself [#check-yourself] A Network Firewall endpoint costs about $0.40 an hour per AZ, so instead: Deploy AWS Network Firewall in the VPC's internet path with a stateful domain list rule group allowing only that domain, and send alert logs to CloudWatch Logs or S3. ## AWS documentation [#aws-documentation] - [What is AWS Network Firewall?](https://docs.aws.amazon.com/network-firewall/latest/developerguide/what-is-aws-network-firewall.html) # Networking costs (/docs/vpc/networking-costs) ## Networking costs per GB, simplified [#networking-costs-per-gb-simplified]
![Data transfer costs, simplified: traffic between instances in the same AZ over private IPs is free; between AZs it costs about 0.01 dollars per GB in each direction over private IPs, and 0.02 over public or Elastic IPs; between Regions it costs about 0.02 dollars per GB](/diagrams/vpc-transfer-costs.light.svg) ![Data transfer costs, simplified: traffic between instances in the same AZ over private IPs is free; between AZs it costs about 0.01 dollars per GB in each direction over private IPs, and 0.02 over public or Elastic IPs; between Regions it costs about 0.02 dollars per GB](/diagrams/vpc-transfer-costs.dark.svg)
Stay in the AZ and use private IPs to pay least.
- Traffic **in** to AWS: **free**. - Between instances in the **same AZ** over **private IPs**: **free**. - Between **AZs**: **$0.01 per GB** (in each direction) using private IPs; **$0.02 per GB** using public or Elastic IPs. - Between **Regions**: **$0.02 per GB**. - **Use private IPs instead of public IPs** for good savings and better network performance. - **Use the same AZ** for maximum savings (at the cost of high availability). ## Minimizing egress traffic network cost [#minimizing-egress-traffic-network-cost] - **Egress traffic:** outbound traffic (from AWS to outside). - **Ingress traffic:** inbound traffic, from outside to AWS (typically free). - Try to **keep as much internet traffic within AWS** as possible to minimize costs. For example, an application in a corporate data center queries a database in AWS: if the query returns 100 MB that the app reduces to a 50 KB result, **move the application into AWS** so only the 50 KB leaves AWS. - **Direct Connect locations that are co-located in the same AWS Region** result in lower cost for egress network. ## S3 data transfer pricing (USA) [#s3-data-transfer-pricing-usa] - **S3 ingress:** free. - **S3 to the internet:** **$0.09 per GB**. - **S3 Transfer Acceleration:** - faster transfer times (50 to 500% better); - additional cost on top of data transfer pricing: **+$0.04 to $0.08 per GB**. - **S3 to CloudFront:** **$0.00 per GB**. - **CloudFront to the internet:** **$0.085 per GB** (slightly cheaper than S3): - caching capability (lower latency); - reduces costs associated with S3 request pricing (7× cheaper with CloudFront). - **S3 Cross-Region Replication:** **$0.02 per GB**. ## NAT gateway vs gateway VPC endpoint [#nat-gateway-vs-gateway-vpc-endpoint]
![Reaching S3 from private subnets: through a NAT gateway you pay about 0.045 dollars per hour plus 0.045 dollars per GB processed; through a gateway VPC endpoint for S3 in the same Region the endpoint is free](/diagrams/vpc-nat-vs-endpoint-cost.light.svg) ![Reaching S3 from private subnets: through a NAT gateway you pay about 0.045 dollars per hour plus 0.045 dollars per GB processed; through a gateway VPC endpoint for S3 in the same Region the endpoint is free](/diagrams/vpc-nat-vs-endpoint-cost.dark.svg)
Same S3 access, very different bill.
In us-east-1: - **NAT gateway:** **$0.045 per hour** and **$0.045 per GB** of data processed; plus $0.09 per GB data transfer out to S3 cross-Region ($0.00 same-Region). - **Gateway VPC endpoint:** **no cost** for using it (only standard same-Region data transfer). For heavy S3 or DynamoDB traffic from private subnets, a **gateway endpoint** is the cost answer. Since **February 2024**, AWS charges **$0.005 per hour for every public IPv4 address** (about $3.60 a month), whether it's attached to an instance, a load balancer, a NAT gateway or idle as an Elastic IP. Using private subnets, endpoints and IPv6 cuts this cost. ## Real-world examples [#real-world-examples] - **A log pipeline** in private subnets sends 20 TB a month to S3 through a NAT gateway: about $900 a month in NAT processing alone. An S3 gateway endpoint makes it $0. - **A website** serves images from S3 through CloudFront: S3 to CloudFront is free, and CloudFront's per-GB rate and caching cut both transfer and request costs. ## Exam tips [#exam-tips] - **"Reduce data transfer cost between instances"** → same AZ, private IPs. - **"Reduce cost of private instances accessing S3 or DynamoDB"** → gateway VPC endpoint instead of NAT gateway. - **"Reduce S3 egress cost for global users"** → CloudFront in front of S3. - **"Reduce egress from AWS to on premises"** → process data in AWS and send only results; Direct Connect. ## Common traps [#common-traps] - **"Traffic between AZs is free."** It costs about $0.01 per GB each way. - **"Using public IPs inside AWS costs the same."** Public or Elastic IPs between AZs cost more ($0.02 per GB). ## AWS documentation [#aws-documentation] - [Amazon VPC pricing](https://aws.amazon.com/vpc/pricing/) - [Amazon EC2 On-Demand pricing: data transfer](https://aws.amazon.com/ec2/pricing/on-demand/) - [Overview of data transfer costs for common architectures](https://aws.amazon.com/blogs/architecture/overview-of-data-transfer-costs-for-common-architectures/) # Site-to-Site VPN and Client VPN (/docs/vpc/site-to-site-vpn) ## AWS Site-to-Site VPN [#aws-site-to-site-vpn]
![AWS Site-to-Site VPN: a virtual private gateway attached to the VPC, with route propagation enabled in the subnet route table, connects through two IPsec tunnels over the public internet to the customer gateway in the corporate data center, which uses a public IP address or the public IP of a NAT device with NAT traversal](/diagrams/vpc-site-to-site-vpn.light.svg) ![AWS Site-to-Site VPN: a virtual private gateway attached to the VPC, with route propagation enabled in the subnet route table, connects through two IPsec tunnels over the public internet to the customer gateway in the corporate data center, which uses a public IP address or the public IP of a NAT device with NAT traversal](/diagrams/vpc-site-to-site-vpn.dark.svg)
An encrypted link over the internet.
**[AWS Site-to-Site VPN](/docs/glossary#term-aws-site-to-site-vpn)** connects your data center to a VPC with an **encrypted IPsec connection over the public internet**. - **Virtual private gateway (VGW):** - the VPN concentrator on the **AWS side** of the VPN connection; - the VGW is created and **attached to the VPC** you want to connect; - you can customize the **ASN** (Autonomous System Number). - **Customer gateway (CGW):** a software application or physical device on the **customer side** of the VPN connection. - Each VPN connection has **two tunnels** for high availability, each up to **1.25 Gbps**. - A **transit gateway** can also be the AWS side of the VPN (see [ECMP](/docs/vpc/transit-gateway#site-to-site-vpn-ecmp)). ## Site-to-Site VPN connections [#site-to-site-vpn-connections] - **Customer gateway device (on premises):** what IP address to use? - a **public internet-routable IP address** for your customer gateway device; - if it's behind a **NAT device** enabled for NAT traversal (**NAT-T**), use the **public IP address of the NAT device**. - **Important step:** enable **route propagation** for the virtual private gateway in the route table associated with your subnets. - If you need to **ping** your EC2 instances from on premises, make sure you add the **ICMP protocol** to the inbound rules of your security groups. Site-to-Site VPN now offers **Large Bandwidth Tunnels** of up to **5 Gbps** each (instead of 1.25 Gbps), for VPN connections attached to a **transit gateway** or **Cloud WAN**. The exam uses 1.25 Gbps per tunnel. ## AWS VPN CloudHub [#aws-vpn-cloudhub]
![AWS VPN CloudHub: several sites, each with its own customer gateway and VPN connection, connect to the same virtual private gateway, which acts as a hub so the sites can talk to each other and to the VPC over the internet](/diagrams/vpc-cloudhub.light.svg) ![AWS VPN CloudHub: several sites, each with its own customer gateway and VPN connection, connect to the same virtual private gateway, which acts as a hub so the sites can talk to each other and to the VPC over the internet](/diagrams/vpc-cloudhub.dark.svg)
One VGW as the hub for all your sites.
**[VPN CloudHub](/docs/glossary#term-aws-vpn-cloudhub)**: - provides secure communication **between multiple sites**, if you have multiple VPN connections; - a **low-cost hub-and-spoke** model for primary or secondary network connectivity between different locations (VPN only); - it's a VPN connection, so it goes over the **public internet**; - to set it up, connect **multiple VPN connections on the same VGW**, set up **dynamic routing** (BGP, a unique ASN per customer gateway) and configure route tables. ## AWS Client VPN [#aws-client-vpn] AWS Client VPN is on the exam guide's in-scope list but not in the course slides. This section is written from the AWS documentation. **[AWS Client VPN](/docs/glossary#term-aws-client-vpn)** is a **managed, client-based VPN** for **people** rather than sites. - Users install an **OpenVPN-based client** on their laptop and connect from anywhere. - They reach resources in the **VPC**, and through it **peered VPCs** and **on-premises networks** (over Site-to-Site VPN or Direct Connect), or even the internet. - Authentication with **Active Directory**, **SAML** federation (single sign-on) or **mutual certificates**. - Scales automatically; you pay per endpoint association hour and per connected client hour. Site-to-Site VPN connects **networks**; Client VPN connects **individual users**. ## Exam tips [#exam-tips] - **"Connect the data center to AWS quickly, encrypted, over the internet"** → Site-to-Site VPN (VGW + CGW). - **"VPN up but no traffic"** → enable route propagation; check security groups (ICMP for ping). - **"Customer gateway behind NAT"** → use the NAT device's public IP with NAT-T. - **"Connect many branch offices to each other cheaply"** → VPN CloudHub. - **"Remote employees need secure access to the VPC"** → AWS Client VPN. ## Common traps [#common-traps] - **"Site-to-Site VPN goes over a private line."** It's over the public internet (encrypted); the private line is Direct Connect. - **"Client VPN connects two offices."** That's Site-to-Site VPN. ## Check yourself [#check-yourself] A VPN connection costs about $0.05 an hour and needs an on-premises device, so instead: Enable route propagation for the virtual private gateway in the private subnet's route table (or add static routes), and check that the security groups allow the on-premises CIDR (including ICMP for ping). ## AWS documentation [#aws-documentation] - [What is AWS Site-to-Site VPN?](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) - [Site-to-Site VPN quotas](https://docs.aws.amazon.com/vpn/latest/s2svpn/vpn-limits.html) - [Secure communication between sites using VPN CloudHub](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPN_CloudHub.html) - [What is AWS Client VPN?](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/what-is.html) # AWS Transit Gateway (/docs/vpc/transit-gateway) ## Why it exists [#why-it-exists] With a few VPCs, peering works. With dozens of VPCs, VPN connections and Direct Connect, a **mesh** of peerings and VPNs becomes impossible to manage: every pair needs its own connection, because peering isn't transitive. ## What it is [#what-it-is]
![AWS Transit Gateway: one hub with route tables connects VPCs from several accounts, shared with Resource Access Manager, plus a Direct Connect gateway, Site-to-Site VPN connections and a peered transit gateway in another Region, all transitively](/diagrams/vpc-transit-gateway.light.svg) ![AWS Transit Gateway: one hub with route tables connects VPCs from several accounts, shared with Resource Access Manager, plus a Direct Connect gateway, Site-to-Site VPN connections and a peered transit gateway in another Region, all transitively](/diagrams/vpc-transit-gateway.dark.svg)
One hub instead of a mesh.
**[AWS Transit Gateway](/docs/glossary#term-aws-transit-gateway)** gives **transitive peering between thousands of VPCs and on premises**, with a **hub-and-spoke (star)** connection. - A **Regional** resource, which can work **cross-Region**. - **Share it cross-account** using **[Resource Access Manager (RAM)](/docs/identity/ram)**. - You can **peer transit gateways across Regions**. - **Route tables:** limit which VPC can talk with which other VPC. - Works with **Direct Connect gateway** and **VPN connections**. - Supports **IP multicast** (not supported by any other AWS service). ## Site-to-Site VPN ECMP [#site-to-site-vpn-ecmp] - **ECMP** = Equal-Cost Multi-Path routing: a routing strategy that forwards a packet over **multiple best paths**. - **Use case:** create **multiple Site-to-Site VPN connections** to **increase the bandwidth** of your connection to AWS. **Throughput with ECMP:** - **VPN to a virtual private gateway:** 1 VPN connection (2 tunnels) = 1 VPC; **1.25 Gbps** (only one tunnel is used). - **VPN to a transit gateway:** 1 VPN connection reaches **many VPCs**, and ECMP uses both tunnels: - 1 VPN = **2.5 Gbps**; - 2 VPNs = **5.0 Gbps**; - 3 VPNs = **7.5 Gbps**. - You pay **per GB of data processed** by the transit gateway. ## Share Direct Connect between accounts [#share-direct-connect-between-accounts] A single **Direct Connect** connection can serve VPCs in **many accounts**: Direct Connect location → **transit VIF** → **Direct Connect gateway** → **transit gateway**, which is attached to VPCs in account 1, account 2… You use **RAM** to share the transit gateway with the other accounts. ## Real-world examples [#real-world-examples] - **A company with 80 VPCs** in 20 accounts attaches them all to one transit gateway shared through RAM, with route tables keeping production and development apart, and one Direct Connect gateway for the data centers. ## Exam tips [#exam-tips] - **"Connect many VPCs and on premises, transitive, hub-and-spoke"** → Transit Gateway. - **"IP multicast"** → Transit Gateway. - **"Increase VPN bandwidth beyond 1.25 Gbps"** → several Site-to-Site VPNs to a transit gateway with ECMP. - **"Share one Direct Connect with many accounts' VPCs"** → transit VIF + DX gateway + transit gateway shared with RAM. - **"Isolate some VPCs from others"** → transit gateway route tables. ## Common traps [#common-traps] - **"Peering is transitive through a hub VPC."** Only Transit Gateway gives transitive routing. - **"A VPN to a virtual private gateway uses ECMP."** ECMP across tunnels and connections needs a transit gateway. ## Check yourself [#check-yourself] A transit gateway attachment costs about $0.05 an hour, so instead: Create several Site-to-Site VPN connections to a transit gateway and enable ECMP: each VPN gives about 2.5 Gbps across its two tunnels, so two connections give about 5 Gbps. ## AWS documentation [#aws-documentation] - [What is Amazon VPC Transit Gateways?](https://docs.aws.amazon.com/vpc/latest/tgw/what-is-transit-gateway.html) - [Transit Gateway quotas](https://docs.aws.amazon.com/vpc/latest/tgw/transit-gateway-quotas.html) # VPC and subnets (/docs/vpc/vpc-and-subnets) ## Default VPC [#default-vpc] - All new AWS accounts have a **default VPC** in every Region. - New EC2 instances are launched into the default VPC if no subnet is specified. - The default VPC has **internet connectivity**, and all EC2 instances inside it get **public IPv4 addresses**. - They also get a **public and a private IPv4 DNS name**. ## VPC in AWS (IPv4) [#vpc-in-aws-ipv4] **[VPC](/docs/glossary#term-amazon-vpc)** = Virtual Private Cloud. - You can have **multiple VPCs in an AWS Region** (5 per Region by default, a soft limit you can raise). - Each VPC has a **primary CIDR**, and you can add more: **5 CIDRs per VPC** by default. Each CIDR: - minimum size **/28** (16 IP addresses); - maximum size **/16** (65,536 IP addresses). - Use the **private IPv4 ranges**: - `10.0.0.0/8`; - `172.16.0.0/12`; - `192.168.0.0/16`. - **Your VPC CIDR should NOT overlap with your other networks** (for example your corporate network), or you can't connect them later. The slides say a VPC can have at most 5 CIDRs and can only use private ranges. Today, 5 CIDRs is the default quota, adjustable **up to 50**. AWS **recommends** the private RFC 1918 ranges but also allows publicly routable CIDRs and `100.64.0.0/10`. For the exam, use private ranges and avoid overlaps. ## Subnets [#subnets]
![Subnets in a VPC: VPC 10.0.0.0/16 spans two Availability Zones; each AZ has a public subnet (10.0.0.0/24 and 10.0.1.0/24) and a private subnet (10.0.2.0/24 and 10.0.3.0/24), because each subnet lives in one AZ](/diagrams/vpc-subnets.light.svg) ![Subnets in a VPC: VPC 10.0.0.0/16 spans two Availability Zones; each AZ has a public subnet (10.0.0.0/24 and 10.0.1.0/24) and a private subnet (10.0.2.0/24 and 10.0.3.0/24), because each subnet lives in one AZ](/diagrams/vpc-subnets.dark.svg)
Each subnet lives in one AZ.
- A **[subnet](/docs/glossary#term-subnet)** is a range of IPs (a CIDR inside the VPC CIDR) **tied to one Availability Zone**. - **Public subnet:** its route table has a route to an internet gateway, so instances with public IPs are reachable. - **Private subnet:** no route to an internet gateway. - For high availability, create subnets in **at least two AZs**. ## The 5 reserved IP addresses [#the-5-reserved-ip-addresses]
![The five reserved addresses in subnet 10.0.0.0/24: .0 is the network address, .1 the VPC router, .2 the Amazon DNS, .3 reserved for future use, and .255 the broadcast address, leaving .4 to .254, 251 addresses, for you; if you need 29 IPs, a /27 gives only 27 usable addresses, so choose a /26 with 59](/diagrams/vpc-reserved-ips.light.svg) ![The five reserved addresses in subnet 10.0.0.0/24: .0 is the network address, .1 the VPC router, .2 the Amazon DNS, .3 reserved for future use, and .255 the broadcast address, leaving .4 to .254, 251 addresses, for you; if you need 29 IPs, a /27 gives only 27 usable addresses, so choose a /26 with 59](/diagrams/vpc-reserved-ips.dark.svg)
Always subtract five.
AWS reserves **5 IP addresses (the first 4 and the last 1)** in each subnet. They can't be assigned to an EC2 instance. For `10.0.0.0/24`: - `10.0.0.0`: network address; - `10.0.0.1`: reserved by AWS for the **VPC router**; - `10.0.0.2`: reserved by AWS for mapping to the **Amazon-provided DNS**; - `10.0.0.3`: reserved by AWS for **future use**; - `10.0.0.255`: network **broadcast** address. AWS doesn't support broadcast in a VPC, so the address is reserved. **Exam tip:** if you need **29 IP addresses** for EC2 instances: - you can't choose a subnet of size `/27` (32 IPs − 5 = 27, less than 29); - you need a subnet of size `/26` (64 IPs − 5 = 59, more than 29). ## Real-world examples [#real-world-examples] - **A company** creates VPC `10.20.0.0/16` (its offices use `10.0.0.0/16`, so there's no overlap later for a VPN) with public and private `/24` subnets in three AZs. ## Exam tips [#exam-tips] - **"How many usable IPs in a /28 subnet?"** → 16 − 5 = **11**. - **"Need N IPs"** → pick the smallest subnet where 2^(32−n) − 5 ≥ N. - **"Plan to connect to on premises later"** → choose a VPC CIDR that doesn't overlap. - **"Subnet spans two AZs"** → impossible; one subnet = one AZ. ## Common traps [#common-traps] - **"A /24 subnet gives 256 usable IPs."** 251. - **"The default VPC's instances are private."** They get public IPv4 addresses. ## Hands-on lab: build a VPC with subnets [#hands-on-lab-build-a-vpc-with-subnets] **Goal:** create a VPC with a public and a private subnet. A VPC, subnets, route tables and an internet gateway are free. Don't create a NAT gateway in this lab (it costs about $0.045 an hour). Any Region works. ### Create the VPC [#create-the-vpc] **VPC → Your VPCs → Create VPC → VPC only**: name `saa-vpc`, IPv4 CIDR `10.0.0.0/16`. ### Create two subnets [#create-two-subnets] **Subnets → Create subnet** in `saa-vpc`: `saa-public-a` with `10.0.0.0/24` in the first AZ, and `saa-private-a` with `10.0.16.0/20` in the same AZ. ### Check the numbers [#check-the-numbers] Select each subnet and read **Available IPv4 addresses**. **Expected result:** 251 available addresses in the `/24`, and 4,091 in the `/20` (4,096 − 5). **Clean up:** keep the VPC for the next lab ([internet gateway and route tables](/docs/vpc/internet-gateway-route-tables)), or delete it (deleting the VPC deletes its subnets). ## AWS documentation [#aws-documentation] - [Default VPCs](https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html) - [VPC CIDR blocks](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-cidr-blocks.html) - [Subnet CIDR blocks](https://docs.aws.amazon.com/vpc/latest/userguide/subnet-sizing.html) - [Amazon VPC quotas](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html) # VPC endpoints and PrivateLink (/docs/vpc/vpc-endpoints-privatelink) ## What they are [#what-they-are] - Every AWS service is **publicly exposed** (public URL). - **[VPC endpoints](/docs/glossary#term-vpc-endpoint)** (powered by **AWS PrivateLink**) let you connect to AWS services using a **private network** instead of the public internet. - They're **redundant** and **scale horizontally**. - They **remove the need for an IGW, NAT gateway…** to access AWS services. - In case of issues: - check the **DNS resolution** settings in your VPC; - check the **route tables**. ## Types of endpoints [#types-of-endpoints]
![Interface vs gateway VPC endpoints: an interface endpoint, powered by PrivateLink, is an ENI with a private IP and a security group in your subnet, works with most AWS services such as SNS, SQS, KMS and S3, and costs per hour per AZ plus per GB; a gateway endpoint is a target in your route table, works only with S3 and DynamoDB, and is free](/diagrams/vpc-endpoints.light.svg) ![Interface vs gateway VPC endpoints: an interface endpoint, powered by PrivateLink, is an ENI with a private IP and a security group in your subnet, works with most AWS services such as SNS, SQS, KMS and S3, and costs per hour per AZ plus per GB; a gateway endpoint is a target in your route table, works only with S3 and DynamoDB, and is free](/diagrams/vpc-endpoints.dark.svg)
An ENI for most services, a route for S3 and DynamoDB.
- **Interface endpoints** (powered by PrivateLink): - provision an **ENI** (private IP address) as an entry point (you **must attach a security group**); - support **most AWS services**; - **$ per hour (per AZ) + $ per GB** of data processed. - **Gateway endpoints:** - provision a gateway that must be used **as a target in a route table** (doesn't use security groups); - support **both S3 and DynamoDB** (only those two); - **free**. ## Gateway or interface endpoint for S3? [#gateway-or-interface-endpoint-for-s3] - **Gateway is most likely going to be preferred all the time at the exam.** - **Cost:** free for gateway, $ for interface endpoint. - **Interface endpoint is preferred** if access is required **from on premises** (Site-to-Site VPN or Direct Connect), **a different VPC** or **a different Region**: a gateway endpoint can only be used from inside its own VPC. ## Lambda in a VPC accessing DynamoDB [#lambda-in-a-vpc-accessing-dynamodb]
![A Lambda function in a private subnet reaching DynamoDB: option 1 goes through a NAT gateway and the internet gateway to the public DynamoDB endpoint, which costs NAT charges; option 2, better and free, uses a VPC gateway endpoint for DynamoDB added to the route table](/diagrams/vpc-lambda-dynamodb.light.svg) ![A Lambda function in a private subnet reaching DynamoDB: option 1 goes through a NAT gateway and the internet gateway to the public DynamoDB endpoint, which costs NAT charges; option 2, better and free, uses a VPC gateway endpoint for DynamoDB added to the route table](/diagrams/vpc-lambda-dynamodb.dark.svg)
Skip the NAT gateway with a free endpoint.
DynamoDB is a **public service** from AWS. - **Option 1: access from the public internet.** Because Lambda is in a VPC, it needs a **NAT gateway** in a public subnet and an **internet gateway**. - **Option 2 (better and free): access from the private VPC network.** Deploy a **VPC gateway endpoint for DynamoDB** and change the **route tables**. ## PrivateLink endpoint services [#privatelink-endpoint-services] You can also use **[AWS PrivateLink](/docs/glossary#term-aws-privatelink)** to **expose your own service** to other VPCs (other accounts, customers): - the **service provider** puts the service behind a **Network Load Balancer** (or Gateway Load Balancer) and creates an **endpoint service**; - each **consumer** creates an **interface endpoint** (ENI) in its own VPC. - No VPC peering, public internet, NAT gateway or route table changes are needed, and **CIDRs can overlap**. It's one-way and scales to thousands of consumer VPCs. ## Real-world examples [#real-world-examples] - **A data pipeline** on EC2 in private subnets writes terabytes to S3 every day. Replacing the NAT gateway path with an S3 gateway endpoint removes about $45 of NAT processing per TB. - **A SaaS provider** offers its API to customers' VPCs through a PrivateLink endpoint service behind an NLB. ## Exam tips [#exam-tips] - **"Private access to S3 or DynamoDB from a VPC, cheapest"** → gateway endpoint. - **"Private access to SQS, SNS, KMS, Secrets Manager… from a private subnet"** → interface endpoint. - **"Access S3 privately from on premises over Direct Connect or VPN"** → S3 interface endpoint. - **"Expose a service to many VPCs, overlapping CIDRs, no peering"** → PrivateLink endpoint service with an NLB. - **"Endpoint created but traffic still fails"** → check DNS settings (private DNS) and route tables. ## Common traps [#common-traps] - **"Gateway endpoints for SQS."** Gateway endpoints exist only for S3 and DynamoDB. - **"Use a gateway endpoint from on premises."** It works only from inside its VPC. ## Hands-on lab: an S3 gateway endpoint [#hands-on-lab-an-s3-gateway-endpoint] **Goal:** add a free S3 gateway endpoint to a VPC and see the route it creates. Gateway endpoints are free. Use the default VPC or the lab VPC from [VPC and subnets](/docs/vpc/vpc-and-subnets#hands-on-lab-build-a-vpc-with-subnets). Any Region works. ### Create the endpoint [#create-the-endpoint] **VPC → Endpoints → Create endpoint**: type **AWS services**, service `com.amazonaws..s3` of type **Gateway**, your VPC, and tick its route tables. ### Look at the route table [#look-at-the-route-table] Open one of the route tables you ticked. **Expected result:** a new route whose destination is a prefix list (`pl-…`, the S3 IP ranges) and whose target is the endpoint (`vpce-…`). **Clean up:** delete the endpoint; its routes are removed. ## AWS documentation [#aws-documentation] - [Gateway endpoints](https://docs.aws.amazon.com/vpc/latest/privatelink/gateway-endpoints.html) - [Access AWS services through AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/privatelink-access-aws-services.html) - [AWS PrivateLink for Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/privatelink-interface-endpoints.html) - [AWS PrivateLink pricing](https://aws.amazon.com/privatelink/pricing/) # VPC peering (/docs/vpc/vpc-peering) ## What it is [#what-it-is]
![VPC peering is not transitive: VPC A is peered with VPC B and with VPC C, but B and C can't talk through A; B and C need their own peering connection, and every VPC needs non-overlapping CIDRs and routes in its route tables](/diagrams/vpc-peering.light.svg) ![VPC peering is not transitive: VPC A is peered with VPC B and with VPC C, but B and C can't talk through A; B and C need their own peering connection, and every VPC needs non-overlapping CIDRs and routes in its route tables](/diagrams/vpc-peering.dark.svg)
Every pair that must talk needs its own peering.
**[VPC peering](/docs/glossary#term-vpc-peering)** privately connects **two VPCs** using AWS's network. - Makes them **behave as if they were in the same network**. - They **must not have overlapping CIDRs**. - A VPC peering connection is **NOT transitive**: it must be established for each pair of VPCs that need to communicate. - **You must update the route tables in each VPC's subnets** so EC2 instances can communicate (route the peer's CIDR to the peering connection `pcx-…`). ## Good to know [#good-to-know] - You can create a VPC peering connection between VPCs in **different AWS accounts and Regions** (inter-Region traffic is encrypted and stays on the AWS backbone). - You can **reference a security group in a peered VPC** as a source or destination (it works **cross-account**, but only in the **same Region**): for example, source `123456789012/sg-027ad1f7865d4be76`. - For a peered VPC in a **different Region**, use its **CIDR** in security group rules instead. - No bandwidth bottleneck or single point of failure: peering isn't a gateway. ## Real-world examples [#real-world-examples] - **A shared-services VPC** (Active Directory, monitoring) is peered with three application VPCs. The application VPCs can't talk to each other through it, which is exactly what the security team wants. ## Exam tips [#exam-tips] - **"Connect two VPCs privately"** → VPC peering (with route table updates). - **"VPC A peered with B and C; B can't reach C"** → peering isn't transitive; peer B and C, or use **[Transit Gateway](/docs/vpc/transit-gateway)**. - **"Peering fails to create"** → overlapping CIDRs. - **"Many VPCs (dozens or more)"** → Transit Gateway instead of a mesh of peerings. ## Common traps [#common-traps] - **"Peering works without route changes."** Both sides need routes. - **"Reference a security group from a peered VPC in another Region."** Same Region only; use CIDRs across Regions. ## Check yourself [#check-yourself] Peering two VPCs is free (you pay for cross-AZ or cross-Region data), but needs instances to test, so instead: No: their CIDRs overlap. One VPC must be re-addressed (or the service exposed with PrivateLink, which tolerates overlapping CIDRs). ## AWS documentation [#aws-documentation] - [What is VPC peering?](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html) - [VPC peering basics](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-basics.html) - [Update your security groups to reference peer security groups](https://docs.aws.amazon.com/vpc/latest/peering/vpc-peering-security-groups.html)