Split View: AWS 핵심 서비스 완전 가이드 2025: EC2, S3, RDS, Lambda, VPC, IAM 총정리
AWS 핵심 서비스 완전 가이드 2025: EC2, S3, RDS, Lambda, VPC, IAM 총정리
목차
1. AWS 글로벌 인프라
Amazon Web Services(AWS)는 전 세계에 걸친 방대한 인프라를 운영하고 있다. 2025년 기준으로 33개 이상의 리전(Region), 105개 이상의 가용 영역(Availability Zone), 600개 이상의 엣지 로케이션(Edge Location)을 보유하고 있다.
1.1 리전(Region)
리전은 지리적으로 분리된 독립적인 데이터 센터 클러스터다. 각 리전은 최소 3개의 가용 영역으로 구성된다.
주요 리전:
| 리전 코드 | 위치 | 특징 |
|---|---|---|
| us-east-1 | 미국 버지니아 | 가장 오래되고 서비스가 가장 많음 |
| ap-northeast-2 | 한국 서울 | 한국 사용자 대상 최적 |
| ap-northeast-1 | 일본 도쿄 | 아시아 태평양 주요 거점 |
| eu-west-1 | 아일랜드 | 유럽 주요 거점 |
| ap-southeast-1 | 싱가포르 | 동남아시아 커버리지 |
1.2 리전 선택 기준
리전을 선택할 때 고려해야 할 4가지 핵심 기준이 있다.
- 지연 시간(Latency): 사용자와 가장 가까운 리전 선택
- 규정 준수(Compliance): 데이터 주권법, GDPR 등 법적 요구사항
- 서비스 가용성: 모든 AWS 서비스가 모든 리전에서 제공되지는 않음
- 비용: 리전마다 가격이 다르며, us-east-1이 일반적으로 가장 저렴
1.3 가용 영역(Availability Zone)
가용 영역은 리전 내의 독립적인 데이터 센터다. 각 AZ는 독립된 전원, 냉각, 네트워킹을 갖추고 있으며, AZ 간에는 저지연 네트워크로 연결된다.
리전: ap-northeast-2 (서울)
├── AZ: ap-northeast-2a
├── AZ: ap-northeast-2b
├── AZ: ap-northeast-2c
└── AZ: ap-northeast-2d
1.4 엣지 로케이션과 로컬 존
- 엣지 로케이션: CloudFront CDN 캐시 서버가 위치한 곳. 전 세계 600개 이상
- 로컬 존(Local Zone): 대도시에 위치한 AWS 인프라 확장. 극도로 낮은 지연 시간이 필요한 경우 사용
- Wavelength Zone: 5G 네트워크 엣지에 위치한 AWS 인프라
2. EC2 (Elastic Compute Cloud)
EC2는 AWS에서 가장 기본이 되는 컴퓨팅 서비스다. 가상 서버(인스턴스)를 생성하여 다양한 워크로드를 실행할 수 있다.
2.1 인스턴스 타입
EC2 인스턴스는 사용 목적에 따라 여러 패밀리로 분류된다.
| 패밀리 | 대표 타입 | 용도 | vCPU:메모리 비율 |
|---|---|---|---|
| 범용(General) | t3, m6i, m7g | 웹 서버, 개발 환경 | 1:4 |
| 컴퓨팅 최적화 | c7g, c6i | 배치 처리, HPC | 1:2 |
| 메모리 최적화 | r6g, r6i, x2idn | 인메모리 DB, 캐시 | 1:8 이상 |
| 스토리지 최적화 | i3, i3en, d3 | 데이터 웨어하우스 | 높은 IOPS |
| GPU 인스턴스 | p4d, p5, g5 | ML 학습, 그래픽 | GPU 포함 |
인스턴스 네이밍 규칙:
m6i.xlarge
│││ └─── 크기 (nano, micro, small, medium, large, xlarge, 2xlarge...)
│││
││└───── 추가 기능 (i=Intel, g=Graviton, a=AMD, n=네트워크 강화)
│└────── 세대 (숫자가 클수록 최신)
└─────── 패밀리 (t=버스트, m=범용, c=컴퓨팅, r=메모리...)
2.2 AMI, User Data, Key Pairs
**AMI (Amazon Machine Image)**는 인스턴스를 시작하는 데 필요한 정보를 담은 템플릿이다.
# AWS CLI로 최신 Amazon Linux 2023 AMI 조회
aws ec2 describe-images \
--owners amazon \
--filters "Name=name,Values=al2023-ami-2023.*-x86_64" \
--query "sort_by(Images, &CreationDate)[-1].ImageId" \
--output text
User Data는 인스턴스 시작 시 자동으로 실행되는 스크립트다.
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "Hello from EC2" > /var/www/html/index.html
Key Pairs는 SSH 접속에 사용되는 퍼블릭/프라이빗 키 쌍이다. EC2 인스턴스에는 퍼블릭 키가 저장되고, 사용자는 프라이빗 키로 접속한다.
2.3 요금 모델
EC2는 4가지 주요 요금 모델을 제공한다.
| 요금 모델 | 할인율 | 약정 기간 | 적합한 워크로드 |
|---|---|---|---|
| 온디맨드(On-Demand) | 기준 가격 | 없음 | 단기, 예측 불가 |
| 예약 인스턴스(Reserved) | 최대 72% | 1년 또는 3년 | 안정적, 예측 가능 |
| 스팟 인스턴스(Spot) | 최대 90% | 없음 (중단 가능) | 배치 처리, CI/CD |
| Savings Plans | 최대 72% | 1년 또는 3년 | 유연한 사용 패턴 |
스팟 인스턴스 사용 예시:
# 스팟 인스턴스 요청
aws ec2 request-spot-instances \
--instance-count 1 \
--type "one-time" \
--launch-specification '{
"ImageId": "ami-0abcdef1234567890",
"InstanceType": "c5.xlarge",
"KeyName": "my-key-pair"
}'
2.4 Auto Scaling Group
Auto Scaling Group(ASG)은 트래픽 변화에 따라 EC2 인스턴스 수를 자동으로 조절한다.
핵심 구성 요소:
- Launch Template: 인스턴스 시작 시 사용할 AMI, 인스턴스 타입, 보안 그룹 등 정의
- 스케일링 정책: 언제 확장/축소할지 결정하는 규칙
- Cooldown Period: 스케일링 작업 사이의 대기 시간
# CloudFormation으로 ASG 정의 예시
AutoScalingGroup:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
LaunchTemplate:
LaunchTemplateId: !Ref LaunchTemplate
Version: !GetAtt LaunchTemplate.LatestVersionNumber
MinSize: 2
MaxSize: 10
DesiredCapacity: 4
TargetGroupARNs:
- !Ref ALBTargetGroup
VPCZoneIdentifier:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
스케일링 정책 종류:
- Target Tracking: CPU 사용률 70% 유지 등 목표 지표를 설정
- Step Scaling: 지표 값에 따라 단계적으로 확장/축소
- Scheduled Scaling: 예정된 시간에 인스턴스 수 조절 (예: 매일 오전 9시 확장)
- Predictive Scaling: ML 기반으로 트래픽 패턴을 예측하여 사전 확장
2.5 배치 그룹(Placement Groups)
| 전략 | 설명 | 사용 사례 |
|---|---|---|
| Cluster | 단일 AZ 내 인스턴스를 밀집 배치 | HPC, 저지연 네트워크 |
| Spread | 인스턴스를 서로 다른 하드웨어에 분산 | 고가용성이 중요한 앱 |
| Partition | 인스턴스를 논리적 파티션으로 분할 | Hadoop, Cassandra |
2.6 EBS (Elastic Block Store)
EBS는 EC2 인스턴스에 연결하는 블록 스토리지 볼륨이다.
| 볼륨 타입 | 용도 | 최대 IOPS | 최대 처리량 |
|---|---|---|---|
| gp3 | 범용 SSD (기본) | 16,000 | 1,000 MB/s |
| io2 Block Express | 고성능 SSD | 256,000 | 4,000 MB/s |
| st1 | 처리량 최적화 HDD | 500 | 500 MB/s |
| sc1 | 콜드 HDD | 250 | 250 MB/s |
# EBS 스냅샷 생성
aws ec2 create-snapshot \
--volume-id vol-0123456789abcdef0 \
--description "Daily backup"
# 스냅샷에서 볼륨 복원
aws ec2 create-volume \
--snapshot-id snap-0123456789abcdef0 \
--availability-zone ap-northeast-2a \
--volume-type gp3
3. S3 (Simple Storage Service)
S3는 AWS의 객체 스토리지 서비스로, 무제한에 가까운 용량과 99.999999999%(11 나인) 내구성을 제공한다.
3.1 스토리지 클래스
| 스토리지 클래스 | 가용성 | 최소 보관 기간 | 검색 비용 | 사용 사례 |
|---|---|---|---|---|
| Standard | 99.99% | 없음 | 없음 | 자주 접근하는 데이터 |
| Intelligent-Tiering | 99.9% | 없음 | 모니터링 비용 | 접근 패턴이 변하는 데이터 |
| Standard-IA | 99.9% | 30일 | GB당 과금 | 월 1회 미만 접근 |
| One Zone-IA | 99.5% | 30일 | GB당 과금 | 재생성 가능한 데이터 |
| Glacier Instant | 99.9% | 90일 | GB당 과금 | 분기 1회 접근, 즉시 검색 |
| Glacier Flexible | 99.99% | 90일 | GB당 + 검색 시간 | 연 1-2회, 분-시간 검색 |
| Glacier Deep Archive | 99.99% | 180일 | GB당 + 검색 시간 | 규정 준수용, 12시간 검색 |
3.2 수명 주기 정책
수명 주기 정책으로 데이터를 자동으로 저비용 스토리지 클래스로 전환하거나 삭제할 수 있다.
{
"Rules": [
{
"ID": "ArchiveAndDelete",
"Status": "Enabled",
"Filter": {
"Prefix": "logs/"
},
"Transitions": [
{
"Days": 30,
"StorageClass": "STANDARD_IA"
},
{
"Days": 90,
"StorageClass": "GLACIER"
}
],
"Expiration": {
"Days": 365
}
}
]
}
3.3 버전 관리와 복제
버전 관리(Versioning): 객체의 모든 변경 이력을 보존한다. 실수로 삭제하거나 덮어써도 이전 버전으로 복원할 수 있다.
# 버전 관리 활성화
aws s3api put-bucket-versioning \
--bucket my-bucket \
--versioning-configuration Status=Enabled
# 특정 버전의 객체 조회
aws s3api list-object-versions \
--bucket my-bucket \
--prefix config.json
**교차 리전 복제(CRR)**와 동일 리전 복제(SRR):
- CRR: 재해 복구, 규정 준수를 위해 다른 리전으로 자동 복제
- SRR: 로그 집계, 개발/운영 환경 간 데이터 동기화
3.4 Presigned URL과 이벤트 알림
Presigned URL: 인증 없이 임시로 S3 객체에 접근할 수 있는 URL을 생성한다.
import boto3
s3_client = boto3.client('s3')
# 다운로드용 Presigned URL (1시간 유효)
url = s3_client.generate_presigned_url(
'get_object',
Params={
'Bucket': 'my-bucket',
'Key': 'reports/annual-2025.pdf'
},
ExpiresIn=3600
)
print(f"Download URL: {url}")
S3 이벤트 알림: 객체 생성, 삭제 등의 이벤트를 Lambda, SQS, SNS로 전달한다.
# 이벤트 알림 설정 예시 (CloudFormation)
S3Bucket:
Type: AWS::S3::Bucket
Properties:
NotificationConfiguration:
LambdaConfigurations:
- Event: 's3:ObjectCreated:*'
Filter:
S3Key:
Rules:
- Name: prefix
Value: uploads/
Function: !GetAtt ProcessingFunction.Arn
3.5 S3 Select와 Transfer Acceleration
- S3 Select: SQL 쿼리로 객체 내부의 특정 데이터만 추출. CSV, JSON, Parquet 지원
- S3 Transfer Acceleration: CloudFront 엣지 로케이션을 활용하여 장거리 업로드 속도 향상
3.6 정적 웹사이트 호스팅
S3를 사용하여 정적 웹사이트를 호스팅할 수 있다.
# 버킷을 정적 웹사이트로 설정
aws s3 website s3://my-website-bucket/ \
--index-document index.html \
--error-document error.html
# 웹사이트 파일 동기화
aws s3 sync ./build/ s3://my-website-bucket/ \
--delete \
--cache-control "max-age=31536000"
4. VPC (Virtual Private Cloud)
VPC는 AWS 클라우드 내에서 논리적으로 격리된 가상 네트워크를 구성할 수 있게 해준다.
4.1 CIDR 표기법과 서브넷
CIDR(Classless Inter-Domain Routing)로 IP 주소 범위를 정의한다.
10.0.0.0/16 → 65,536개 IP (10.0.0.0 ~ 10.0.255.255)
10.0.1.0/24 → 256개 IP (10.0.1.0 ~ 10.0.1.255)
10.0.1.0/28 → 16개 IP (10.0.1.0 ~ 10.0.1.15)
퍼블릭 서브넷 vs 프라이빗 서브넷:
- 퍼블릭 서브넷: Internet Gateway로의 라우팅이 있는 서브넷. 웹 서버, 로드 밸런서 배치
- 프라이빗 서브넷: 인터넷에 직접 접근이 불가능한 서브넷. DB, 애플리케이션 서버 배치
4.2 3-Tier 아키텍처 설계
┌─────────────────────────────────────────────────────────┐
│ VPC: 10.0.0.0/16 │
│ │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ Public Subnet │ │ Public Subnet │ │
│ │ 10.0.1.0/24 │ │ 10.0.2.0/24 │ │
│ │ (AZ-a) │ │ (AZ-b) │ │
│ │ │ │ │ │
│ │ ┌──────────────┐ │ │ ┌──────────────┐ │ │
│ │ │ ALB / NAT GW │ │ │ │ ALB / NAT GW │ │ │
│ │ └──────────────┘ │ │ └──────────────┘ │ │
│ └────────────────────┘ └────────────────────┘ │
│ │ │ │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ Private Subnet │ │ Private Subnet │ │
│ │ (App) 10.0.3.0/24 │ │ (App) 10.0.4.0/24 │ │
│ │ │ │ │ │
│ │ ┌──────────────┐ │ │ ┌──────────────┐ │ │
│ │ │ EC2 / ECS │ │ │ │ EC2 / ECS │ │ │
│ │ └──────────────┘ │ │ └──────────────┘ │ │
│ └────────────────────┘ └────────────────────┘ │
│ │ │ │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ Private Subnet │ │ Private Subnet │ │
│ │ (DB) 10.0.5.0/24 │ │ (DB) 10.0.6.0/24 │ │
│ │ │ │ │ │
│ │ ┌──────────────┐ │ │ ┌──────────────┐ │ │
│ │ │ RDS Primary │ │ │ │ RDS Standby │ │ │
│ │ └──────────────┘ │ │ └──────────────┘ │ │
│ └────────────────────┘ └────────────────────┘ │
│ │
│ ┌──────────┐ │
│ │ IGW │ ← Internet Gateway │
│ └──────────┘ │
└─────────────────────────────────────────────────────────┘
4.3 Internet Gateway와 NAT Gateway
- Internet Gateway(IGW): VPC와 인터넷 간의 통신을 가능하게 하는 게이트웨이
- NAT Gateway: 프라이빗 서브넷의 인스턴스가 인터넷에 접근할 수 있게 하되, 외부에서의 인바운드 접근은 차단
# NAT Gateway 생성
aws ec2 create-nat-gateway \
--subnet-id subnet-0123456789abcdef0 \
--allocation-id eipalloc-0123456789abcdef0
4.4 보안 그룹 vs NACL
| 항목 | 보안 그룹(Security Group) | 네트워크 ACL(NACL) |
|---|---|---|
| 적용 범위 | 인스턴스(ENI) 수준 | 서브넷 수준 |
| 상태 | Stateful (응답 자동 허용) | Stateless (명시적 허용 필요) |
| 규칙 유형 | 허용 규칙만 | 허용 + 거부 규칙 |
| 규칙 평가 | 모든 규칙 평가 | 번호 순서대로 평가 |
| 기본 동작 | 모든 아웃바운드 허용, 인바운드 거부 | 모든 트래픽 허용 |
# 보안 그룹 생성 및 규칙 추가
aws ec2 create-security-group \
--group-name web-sg \
--description "Web server security group" \
--vpc-id vpc-0123456789abcdef0
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 443 \
--cidr 0.0.0.0/0
4.5 VPC 피어링과 Transit Gateway
- VPC Peering: 두 VPC 간 프라이빗 네트워크 연결. 전이적 라우팅 불가(A-B, B-C 연결 시 A-C 직접 통신 불가)
- Transit Gateway: 중앙 허브를 통해 여러 VPC와 온프레미스 네트워크를 연결. 전이적 라우팅 지원
4.6 VPC 엔드포인트
VPC 엔드포인트를 사용하면 인터넷을 거치지 않고 AWS 서비스에 접근할 수 있다.
| 타입 | 지원 서비스 | 비용 |
|---|---|---|
| Gateway Endpoint | S3, DynamoDB | 무료 |
| Interface Endpoint | 대부분의 AWS 서비스 | 시간당 + 데이터 전송 비용 |
4.7 VPC Flow Logs
VPC Flow Logs는 네트워크 인터페이스에서 송수신되는 IP 트래픽 정보를 캡처한다.
# Flow Log 레코드 예시
# version account-id interface-id srcaddr dstaddr srcport dstport protocol packets bytes start end action log-status
2 123456789012 eni-abc123 10.0.1.5 52.94.76.1 49761 443 6 12 1024 1625000000 1625000060 ACCEPT OK
5. IAM (Identity and Access Management)
IAM은 AWS 리소스에 대한 접근을 안전하게 제어하는 서비스다.
5.1 IAM 구성 요소
- 사용자(User): 개별 사람 또는 서비스를 나타내는 엔티티
- 그룹(Group): 동일한 권한이 필요한 사용자들의 모음
- 역할(Role): AWS 서비스나 외부 사용자가 임시로 맡을 수 있는 권한 집합
- 정책(Policy): JSON 형식으로 권한을 정의한 문서
5.2 정책 JSON 구조
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowS3ReadAccess",
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::my-bucket",
"arn:aws:s3:::my-bucket/*"
],
"Condition": {
"IpAddress": {
"aws:SourceIp": "203.0.113.0/24"
}
}
}
]
}
정책 구성 요소:
- Effect:
Allow또는Deny - Action: 허용/거부할 API 작업 (예:
s3:GetObject) - Resource: 대상 리소스의 ARN
- Condition: 조건부 적용 (IP, 시간, 태그 등)
5.3 EC2용 IAM 역할 (인스턴스 프로파일)
EC2 인스턴스에 IAM 역할을 부여하면 액세스 키 없이 AWS 서비스에 접근할 수 있다.
# 인스턴스 프로파일 생성 및 역할 연결
aws iam create-instance-profile \
--instance-profile-name EC2-S3-ReadOnly
aws iam add-role-to-instance-profile \
--instance-profile-name EC2-S3-ReadOnly \
--role-name S3ReadOnlyRole
# EC2 인스턴스에 프로파일 연결
aws ec2 associate-iam-instance-profile \
--instance-id i-0123456789abcdef0 \
--iam-instance-profile Name=EC2-S3-ReadOnly
5.4 교차 계정 접근
다른 AWS 계정의 리소스에 접근할 때는 IAM 역할의 신뢰 관계(Trust Policy)를 활용한다.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::111122223333:root"
},
"Action": "sts:AssumeRole"
}
]
}
5.5 IAM 보안 모범 사례
- 루트 계정 사용 금지: 루트 계정에는 MFA만 설정하고 일상 작업에는 사용하지 않는다
- MFA 활성화: 모든 사용자에게 다중 인증(MFA)을 요구한다
- 최소 권한 원칙: 필요한 최소한의 권한만 부여한다
- 액세스 키 로테이션: 90일마다 액세스 키를 교체한다
- IAM Access Analyzer: 외부 접근 가능한 리소스를 분석하고 모니터링한다
- 임시 자격 증명 사용: 장기 자격 증명 대신 STS를 통한 임시 자격 증명을 사용한다
6. RDS (Relational Database Service)
RDS는 관리형 관계형 데이터베이스 서비스로, 패치, 백업, 장애 조치를 자동으로 처리한다.
6.1 지원 엔진
| 엔진 | 최신 버전 | 특징 |
|---|---|---|
| Amazon Aurora | MySQL 8.0/PostgreSQL 16 호환 | 상용 DB 성능, 오픈소스 가격 |
| MySQL | 8.0 | 가장 보편적인 오픈소스 DB |
| PostgreSQL | 16 | 고급 기능, 확장성 |
| MariaDB | 10.11 | MySQL 호환, 커뮤니티 주도 |
| Oracle | 19c/21c | 엔터프라이즈 워크로드 |
| SQL Server | 2022 | Windows 기반 애플리케이션 |
6.2 Multi-AZ와 Read Replica
Multi-AZ (고가용성):
┌──────────────────┐ 동기 복제 ┌──────────────────┐
│ Primary (AZ-a) │ ──────────────── │ Standby (AZ-b) │
│ │ │ │
│ 읽기 + 쓰기 │ 자동 장애조치 │ 대기 (접근 불가) │
└──────────────────┘ └──────────────────┘
Read Replica (읽기 확장):
┌──────────────────┐
│ Read Replica 1 │ ← 읽기 전용
┌──▶│ (같은 리전) │
│ └──────────────────┘
┌──────────────┤ ┌──────────────────┐
│ Primary │──▶│ Read Replica 2 │ ← 읽기 전용
│ (읽기+쓰기) │ │ (같은 리전) │
└──────────────┤ └──────────────────┘
│ ┌──────────────────┐
└──▶│ Read Replica 3 │ ← 교차 리전 복제
│ (다른 리전) │
└──────────────────┘
6.3 Aurora Serverless v2
Aurora Serverless v2는 워크로드에 따라 자동으로 용량을 조절한다.
- ACU(Aurora Capacity Unit): 0.5~128 ACU 범위에서 자동 스케일링
- 초 단위 과금: 실제 사용한 ACU만큼만 비용 발생
- 혼합 구성: 프로비저닝된 인스턴스와 서버리스 인스턴스를 동일 클러스터에 혼합 가능
# Aurora Serverless v2 클러스터 생성
aws rds create-db-cluster \
--db-cluster-identifier my-aurora-cluster \
--engine aurora-postgresql \
--engine-version 16.1 \
--serverless-v2-scaling-configuration MinCapacity=0.5,MaxCapacity=16 \
--master-username admin \
--master-user-password MySecurePassword123
6.4 자동 백업과 파라미터 그룹
- 자동 백업: 매일 자동 스냅샷 생성 (최대 35일 보관)
- 특정 시점 복원(PITR): 5분 단위로 특정 시점의 데이터를 복원
- 파라미터 그룹: DB 엔진 설정을 커스터마이즈
6.5 RDS Proxy
RDS Proxy는 데이터베이스 연결을 풀링하여 관리한다. Lambda와 같이 짧은 수명의 연결이 많은 서버리스 환경에서 특히 유용하다.
Lambda 함수들 ──▶ RDS Proxy ──▶ RDS 인스턴스
(수천 개 연결) (커넥션 풀링) (소수의 연결)
7. Lambda (서버리스 컴퓨팅)
Lambda는 서버를 프로비저닝하거나 관리할 필요 없이 코드를 실행할 수 있는 서버리스 컴퓨팅 서비스다.
7.1 이벤트 기반 아키텍처
Lambda는 다양한 AWS 서비스의 이벤트에 의해 트리거된다.
┌─────────────┐ ┌──────────┐ ┌─────────────┐
│ API Gateway │────▶│ │────▶│ DynamoDB │
└─────────────┘ │ │ └─────────────┘
│ │
┌─────────────┐ │ Lambda │ ┌─────────────┐
│ S3 Event │────▶│ Function │────▶│ S3 │
└─────────────┘ │ │ └─────────────┘
│ │
┌─────────────┐ │ │ ┌─────────────┐
│ SQS / SNS │────▶│ │────▶│ SQS / SNS │
└─────────────┘ │ │ └─────────────┘
│ │
┌─────────────┐ │ │ ┌─────────────┐
│ EventBridge │────▶│ │────▶│ Step Func. │
└─────────────┘ └──────────┘ └─────────────┘
7.2 Lambda 함수 예시
import json
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
def lambda_handler(event, context):
"""API Gateway에서 호출되는 Lambda 함수"""
http_method = event['httpMethod']
path = event['path']
if http_method == 'GET':
response = table.scan()
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps(response['Items'], default=str)
}
elif http_method == 'POST':
body = json.loads(event['body'])
table.put_item(Item=body)
return {
'statusCode': 201,
'body': json.dumps({'message': 'Created successfully'})
}
return {
'statusCode': 400,
'body': json.dumps({'message': 'Unsupported method'})
}
7.3 콜드 스타트 최적화
Lambda 함수가 처음 호출되거나 오랜 시간 후 호출될 때 콜드 스타트가 발생한다.
최적화 방법:
- Provisioned Concurrency: 미리 인스턴스를 워밍업하여 콜드 스타트 제거
- 메모리 크기 최적화: 메모리를 늘리면 CPU도 비례하여 증가
- 패키지 크기 축소: 불필요한 의존성 제거
- Lambda SnapStart: Java 함수의 스냅샷 기반 초기화 (최대 10배 빠른 시작)
- Lambda Layers: 공통 라이브러리를 Layer로 분리하여 재사용
# Provisioned Concurrency 설정
aws lambda put-provisioned-concurrency-config \
--function-name my-function \
--qualifier prod \
--provisioned-concurrent-executions 10
7.4 Lambda@Edge
Lambda@Edge는 CloudFront 엣지 로케이션에서 Lambda 함수를 실행한다. A/B 테스팅, 헤더 조작, URL 리다이렉트 등에 활용된다.
7.5 요금 모델
- 요청 수: 월 100만 건 무료, 이후 100만 건당 약 0.20 USD
- 실행 시간: GB-초 단위 과금 (메모리 x 실행 시간)
- Provisioned Concurrency: 프로비저닝 용량에 따른 추가 비용
8. DynamoDB
DynamoDB는 완전관리형 NoSQL 데이터베이스로, 밀리초 단위의 일관된 응답 시간을 제공한다.
8.1 데이터 모델
┌─────────────────────────────────────────────┐
│ Table: Orders │
│ │
│ Partition Key: userId (String) │
│ Sort Key: orderDate (String) │
│ │
│ ┌──────────┬────────────┬────────┬────────┐│
│ │ userId │ orderDate │ total │ status ││
│ ├──────────┼────────────┼────────┼────────┤│
│ │ user-001 │ 2025-01-15 │ 29900 │ shipped││
│ │ user-001 │ 2025-03-20 │ 15000 │ pending││
│ │ user-002 │ 2025-02-10 │ 89000 │ delivered│
│ └──────────┴────────────┴────────┴────────┘│
│ │
│ GSI: StatusIndex │
│ Partition Key: status │
│ Sort Key: orderDate │
└─────────────────────────────────────────────┘
인덱스:
- GSI (Global Secondary Index): 다른 파티션 키와 정렬 키로 쿼리 가능
- LSI (Local Secondary Index): 동일 파티션 키, 다른 정렬 키 (테이블 생성 시에만 추가 가능)
8.2 용량 모드
| 모드 | 특징 | 적합한 사용 사례 |
|---|---|---|
| 온디맨드 | 자동 스케일링, 사용량 기반 과금 | 예측 불가한 트래픽 |
| 프로비저닝 | RCU/WCU 미리 설정, Auto Scaling 가능 | 예측 가능한 트래픽, 비용 절감 |
8.3 DynamoDB Streams와 TTL
- DynamoDB Streams: 테이블 변경 사항을 실시간으로 캡처. Lambda 트리거로 이벤트 처리
- TTL (Time to Live): 만료 시간을 설정하여 오래된 항목을 자동 삭제
8.4 단일 테이블 설계 패턴
DynamoDB에서는 단일 테이블에 여러 엔티티를 저장하는 패턴이 권장된다.
PK | SK | 데이터
------------|-----------------|------------------
USER#001 | PROFILE | name, email, ...
USER#001 | ORDER#2025-001 | total, status, ...
USER#001 | ORDER#2025-002 | total, status, ...
ORG#ABC | METADATA | orgName, plan, ...
ORG#ABC | MEMBER#001 | role, joinedAt, ...
9. CloudFront (CDN)
CloudFront는 AWS의 CDN(Content Delivery Network) 서비스로, 전 세계 엣지 로케이션에서 콘텐츠를 캐싱하여 빠르게 전달한다.
9.1 배포 구성
사용자 ──▶ CloudFront Edge ──▶ Origin
│ │
캐시 히트 시 캐시 미스 시
즉시 응답 반환 오리진에서 가져옴
오리진 종류:
- S3 버킷 (정적 콘텐츠)
- ALB / EC2 (동적 콘텐츠)
- API Gateway (API)
- 커스텀 오리진 (온프레미스 서버)
9.2 캐시 정책과 Origin Shield
캐시 정책(Cache Policy): 어떤 요소(헤더, 쿼리 스트링, 쿠키)를 캐시 키에 포함할지 정의한다.
Origin Shield: 오리진 앞에 추가 캐싱 레이어를 두어 오리진 부하를 줄인다.
9.3 Lambda@Edge vs CloudFront Functions
| 항목 | Lambda@Edge | CloudFront Functions |
|---|---|---|
| 실행 위치 | 리전 엣지 캐시 | 엣지 로케이션 |
| 최대 실행 시간 | 5~30초 | 1ms |
| 메모리 | 128~10,240 MB | 2 MB |
| 네트워크 접근 | 가능 | 불가 |
| 비용 | 상대적으로 높음 | 매우 저렴 |
| 사용 사례 | A/B 테스팅, 인증 | URL 리라이트, 헤더 조작 |
10. 컨테이너 서비스
10.1 ECS (Elastic Container Service)
ECS는 Docker 컨테이너를 실행하고 관리하는 오케스트레이션 서비스다.
Fargate vs EC2 시작 유형:
| 항목 | Fargate | EC2 |
|---|---|---|
| 인프라 관리 | AWS가 관리 | 사용자가 관리 |
| 가격 | vCPU + 메모리 기반 | EC2 인스턴스 비용 |
| 스케일링 | 태스크 단위 | 인스턴스 + 태스크 |
| GPU 지원 | 불가 | 가능 |
| 적합한 상황 | 간편한 운영 | GPU, 대규모 비용 최적화 |
10.2 EKS (Elastic Kubernetes Service)
EKS는 관리형 Kubernetes 서비스다. 컨트롤 플레인을 AWS가 관리하며, 워커 노드는 EC2 또는 Fargate로 실행할 수 있다.
10.3 ECR (Elastic Container Registry)
ECR은 Docker 이미지를 저장하는 프라이빗 컨테이너 레지스트리다.
# ECR에 이미지 푸시
aws ecr get-login-password --region ap-northeast-2 | \
docker login --username AWS --password-stdin 123456789012.dkr.ecr.ap-northeast-2.amazonaws.com
docker tag my-app:latest 123456789012.dkr.ecr.ap-northeast-2.amazonaws.com/my-app:latest
docker push 123456789012.dkr.ecr.ap-northeast-2.amazonaws.com/my-app:latest
11. 기타 핵심 서비스
11.1 메시징 서비스
SQS (Simple Queue Service):
- 표준 대기열: 무제한 처리량, 최소 1회 전달 (순서 보장 안 됨)
- FIFO 대기열: 정확히 1회 전달, 순서 보장 (초당 3,000 메시지)
SNS (Simple Notification Service):
- Pub/Sub 메시징 모델
- 다수의 구독자에게 동시 알림 (팬아웃 패턴)
EventBridge:
- 이벤트 기반 아키텍처를 위한 서버리스 이벤트 버스
- 이벤트 패턴 매칭, 스케줄 기반 트리거
- 100개 이상의 AWS 서비스 및 SaaS 통합
11.2 Step Functions
Step Functions는 여러 AWS 서비스를 시각적 워크플로로 조합하는 오케스트레이션 서비스다.
{
"Comment": "주문 처리 워크플로",
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:ap-northeast-2:123456789012:function:validate",
"Next": "ProcessPayment"
},
"ProcessPayment": {
"Type": "Task",
"Resource": "arn:aws:lambda:ap-northeast-2:123456789012:function:payment",
"Next": "ShipOrder",
"Catch": [
{
"ErrorEquals": ["PaymentFailed"],
"Next": "NotifyFailure"
}
]
},
"ShipOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:ap-northeast-2:123456789012:function:ship",
"End": true
},
"NotifyFailure": {
"Type": "Task",
"Resource": "arn:aws:lambda:ap-northeast-2:123456789012:function:notify",
"End": true
}
}
}
11.3 모니터링과 감사
CloudWatch:
- 메트릭 수집 및 대시보드
- 로그 그룹과 로그 인사이트
- 경보(Alarm) 설정 및 자동 대응
CloudTrail:
- 모든 API 호출 기록
- 보안 감사 및 규정 준수
- 이벤트 히스토리 90일 기본 저장
11.4 Route 53
Route 53는 AWS의 관리형 DNS 서비스다.
라우팅 정책:
| 정책 | 설명 |
|---|---|
| Simple | 단일 리소스로 라우팅 |
| Weighted | 가중치 기반 트래픽 분배 |
| Latency | 가장 낮은 지연 시간의 리전으로 라우팅 |
| Failover | 장애 시 대체 리소스로 전환 |
| Geolocation | 사용자 위치 기반 라우팅 |
| Multi-Value | 다수의 건강한 리소스를 반환 |
12. 비용 최적화 전략
12.1 인스턴스 최적화
- Right-sizing: AWS Compute Optimizer를 활용하여 인스턴스 크기 최적화
- Reserved Instances: 안정적 워크로드에 1년/3년 예약으로 최대 72% 절감
- Spot Instances: 중단 가능한 워크로드에 최대 90% 절감
- Savings Plans: 컴퓨팅 사용량 약정으로 유연하게 할인
12.2 스토리지 최적화
- S3 수명 주기 정책으로 자동 아카이빙
- EBS 볼륨 타입 최적화 (gp2에서 gp3로 전환 시 최대 20% 절감)
- 사용하지 않는 EBS 스냅샷과 볼륨 정리
12.3 비용 관리 도구
| 도구 | 기능 |
|---|---|
| Cost Explorer | 비용 분석 및 예측 |
| Budgets | 예산 설정 및 알림 |
| Cost Anomaly Detection | 비정상 비용 자동 감지 |
| Trusted Advisor | 비용 절감 권고사항 제공 |
12.4 태깅 전략
모든 리소스에 일관된 태깅을 적용하여 비용을 팀/프로젝트/환경별로 추적한다.
# 필수 태그 예시
aws ec2 create-tags \
--resources i-0123456789abcdef0 \
--tags \
Key=Environment,Value=Production \
Key=Team,Value=Backend \
Key=Project,Value=UserService \
Key=CostCenter,Value=CC-1234
12.5 Well-Architected Framework
AWS Well-Architected Framework의 6가지 기둥:
- 운영 우수성(Operational Excellence): 자동화, IaC, 관찰 가능성
- 보안(Security): IAM, 암호화, 네트워크 보안
- 안정성(Reliability): Multi-AZ, 자동 복구, 재해 복구
- 성능 효율성(Performance Efficiency): 적절한 리소스 선택, 모니터링
- 비용 최적화(Cost Optimization): 사용한 만큼만 과금, 예약
- 지속 가능성(Sustainability): 에너지 효율, 리소스 최적화
13. 실전 퀴즈
아래 퀴즈로 학습 내용을 점검해보자.
Q1. S3 버킷에 저장된 객체가 30일 후 Standard-IA로, 90일 후 Glacier로 이동하고, 365일 후 삭제되도록 하려면 어떤 기능을 사용해야 하는가?
정답: S3 수명 주기 정책(Lifecycle Policy)
수명 주기 정책을 사용하면 Transition 규칙으로 스토리지 클래스를 자동 전환하고, Expiration 규칙으로 객체를 자동 삭제할 수 있다. 이를 통해 비용을 크게 절감할 수 있다.
Q2. Lambda 함수의 콜드 스타트를 완전히 제거하려면 어떤 기능을 사용해야 하는가?
정답: Provisioned Concurrency
Provisioned Concurrency는 Lambda 실행 환경을 미리 초기화된 상태로 유지하여 콜드 스타트를 완전히 제거한다. 다만 프로비저닝된 용량에 대한 추가 비용이 발생한다.
Q3. VPC에서 프라이빗 서브넷의 인스턴스가 인터넷에 접근하되, 외부에서의 인바운드 접근은 차단하려면 어떤 서비스를 사용해야 하는가?
정답: NAT Gateway
NAT Gateway는 프라이빗 서브넷의 인스턴스가 아웃바운드 인터넷 트래픽을 전송할 수 있게 하면서, 인터넷에서의 인바운드 연결은 차단한다. NAT Gateway는 퍼블릭 서브넷에 배치해야 한다.
Q4. DynamoDB에서 특정 속성 값으로 효율적으로 쿼리하려면 어떤 인덱스를 사용해야 하는가?
정답: GSI (Global Secondary Index)
GSI를 사용하면 기존 테이블의 파티션 키와 정렬 키가 아닌 다른 속성으로도 효율적인 쿼리를 수행할 수 있다. GSI는 테이블 생성 후에도 추가할 수 있다.
Q5. Multi-AZ RDS와 Read Replica의 차이점은 무엇인가?
정답:
- Multi-AZ: 고가용성(HA) 목적. 동기 복제, 자동 장애 조치. Standby에는 읽기 접근 불가.
- Read Replica: 읽기 확장(Scalability) 목적. 비동기 복제. 읽기 전용으로 접근 가능. 교차 리전 복제도 지원.
Multi-AZ는 장애 시 자동으로 Standby로 전환되어 다운타임을 최소화하고, Read Replica는 읽기 트래픽을 분산하여 성능을 향상시킨다.
참고 자료
AWS Core Services Complete Guide 2025: EC2, S3, RDS, Lambda, VPC, IAM Deep Dive
Table of Contents
1. AWS Global Infrastructure
Amazon Web Services (AWS) operates a vast infrastructure spanning the entire globe. As of 2025, AWS has over 33 Regions, 105+ Availability Zones, and 600+ Edge Locations worldwide.
1.1 Regions
A Region is a geographically isolated cluster of independent data centers. Each Region consists of a minimum of 3 Availability Zones.
Key Regions:
| Region Code | Location | Characteristics |
|---|---|---|
| us-east-1 | N. Virginia, USA | Oldest region, most services available |
| eu-west-1 | Ireland | Primary European hub |
| ap-northeast-1 | Tokyo, Japan | Major Asia-Pacific hub |
| ap-southeast-1 | Singapore | Southeast Asia coverage |
| us-west-2 | Oregon, USA | Popular for development and testing |
1.2 Region Selection Criteria
There are four key criteria to consider when selecting a Region:
- Latency: Choose the Region closest to your users
- Compliance: Data sovereignty laws, GDPR, and other legal requirements
- Service Availability: Not all AWS services are available in every Region
- Cost: Pricing varies by Region; us-east-1 is generally the cheapest
1.3 Availability Zones (AZs)
An Availability Zone is an independent data center within a Region. Each AZ has independent power, cooling, and networking, connected to other AZs via low-latency networks.
Region: us-east-1 (N. Virginia)
├── AZ: us-east-1a
├── AZ: us-east-1b
├── AZ: us-east-1c
├── AZ: us-east-1d
├── AZ: us-east-1e
└── AZ: us-east-1f
1.4 Edge Locations and Local Zones
- Edge Locations: Where CloudFront CDN cache servers reside. 600+ worldwide
- Local Zones: AWS infrastructure extensions in major metropolitan areas. Used when ultra-low latency is required
- Wavelength Zones: AWS infrastructure at the edge of 5G networks
2. EC2 (Elastic Compute Cloud)
EC2 is the most fundamental compute service in AWS. You can create virtual servers (instances) to run diverse workloads.
2.1 Instance Types
EC2 instances are classified into several families based on their intended use.
| Family | Representative Types | Use Case | vCPU:Memory Ratio |
|---|---|---|---|
| General Purpose | t3, m6i, m7g | Web servers, dev environments | 1:4 |
| Compute Optimized | c7g, c6i | Batch processing, HPC | 1:2 |
| Memory Optimized | r6g, r6i, x2idn | In-memory DBs, caches | 1:8+ |
| Storage Optimized | i3, i3en, d3 | Data warehousing | High IOPS |
| GPU Instances | p4d, p5, g5 | ML training, graphics | Includes GPU |
Instance Naming Convention:
m6i.xlarge
│││ └─── Size (nano, micro, small, medium, large, xlarge, 2xlarge...)
│││
││└───── Additional features (i=Intel, g=Graviton, a=AMD, n=network enhanced)
│└────── Generation (higher number = newer)
└─────── Family (t=burstable, m=general, c=compute, r=memory...)
2.2 AMI, User Data, Key Pairs
An AMI (Amazon Machine Image) is a template containing the information required to launch an instance.
# Query the latest Amazon Linux 2023 AMI using AWS CLI
aws ec2 describe-images \
--owners amazon \
--filters "Name=name,Values=al2023-ami-2023.*-x86_64" \
--query "sort_by(Images, &CreationDate)[-1].ImageId" \
--output text
User Data is a script that automatically executes when an instance starts.
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "Hello from EC2" > /var/www/html/index.html
Key Pairs are public/private key pairs used for SSH access. The public key is stored on the EC2 instance, and users connect using the private key.
2.3 Pricing Models
EC2 offers four primary pricing models.
| Pricing Model | Discount | Commitment | Best For |
|---|---|---|---|
| On-Demand | Baseline price | None | Short-term, unpredictable |
| Reserved Instances | Up to 72% | 1 or 3 years | Steady, predictable |
| Spot Instances | Up to 90% | None (can be interrupted) | Batch processing, CI/CD |
| Savings Plans | Up to 72% | 1 or 3 years | Flexible usage patterns |
Spot Instance example:
# Request a Spot Instance
aws ec2 request-spot-instances \
--instance-count 1 \
--type "one-time" \
--launch-specification '{
"ImageId": "ami-0abcdef1234567890",
"InstanceType": "c5.xlarge",
"KeyName": "my-key-pair"
}'
2.4 Auto Scaling Group
An Auto Scaling Group (ASG) automatically adjusts the number of EC2 instances based on traffic changes.
Key Components:
- Launch Template: Defines AMI, instance type, security groups, etc. for instance startup
- Scaling Policies: Rules that determine when to scale in/out
- Cooldown Period: Wait time between scaling actions
# ASG definition using CloudFormation
AutoScalingGroup:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
LaunchTemplate:
LaunchTemplateId: !Ref LaunchTemplate
Version: !GetAtt LaunchTemplate.LatestVersionNumber
MinSize: 2
MaxSize: 10
DesiredCapacity: 4
TargetGroupARNs:
- !Ref ALBTargetGroup
VPCZoneIdentifier:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
Types of Scaling Policies:
- Target Tracking: Set a target metric, e.g., maintain 70% CPU utilization
- Step Scaling: Scale in steps based on metric values
- Scheduled Scaling: Adjust instance count at predetermined times (e.g., scale up every weekday at 9 AM)
- Predictive Scaling: ML-based traffic pattern prediction for proactive scaling
2.5 Placement Groups
| Strategy | Description | Use Case |
|---|---|---|
| Cluster | Pack instances closely within a single AZ | HPC, low-latency networking |
| Spread | Distribute instances across distinct hardware | HA-critical applications |
| Partition | Divide instances into logical partitions | Hadoop, Cassandra |
2.6 EBS (Elastic Block Store)
EBS provides block storage volumes that attach to EC2 instances.
| Volume Type | Use Case | Max IOPS | Max Throughput |
|---|---|---|---|
| gp3 | General purpose SSD (default) | 16,000 | 1,000 MB/s |
| io2 Block Express | High-performance SSD | 256,000 | 4,000 MB/s |
| st1 | Throughput-optimized HDD | 500 | 500 MB/s |
| sc1 | Cold HDD | 250 | 250 MB/s |
# Create an EBS snapshot
aws ec2 create-snapshot \
--volume-id vol-0123456789abcdef0 \
--description "Daily backup"
# Restore a volume from snapshot
aws ec2 create-volume \
--snapshot-id snap-0123456789abcdef0 \
--availability-zone us-east-1a \
--volume-type gp3
3. S3 (Simple Storage Service)
S3 is AWS's object storage service, offering virtually unlimited capacity with 99.999999999% (11 nines) durability.
3.1 Storage Classes
| Storage Class | Availability | Min Storage Duration | Retrieval Cost | Use Case |
|---|---|---|---|---|
| Standard | 99.99% | None | None | Frequently accessed data |
| Intelligent-Tiering | 99.9% | None | Monitoring fee | Changing access patterns |
| Standard-IA | 99.9% | 30 days | Per-GB charge | Less than monthly access |
| One Zone-IA | 99.5% | 30 days | Per-GB charge | Reproducible data |
| Glacier Instant | 99.9% | 90 days | Per-GB charge | Quarterly access, instant retrieval |
| Glacier Flexible | 99.99% | 90 days | Per-GB + retrieval time | 1-2x/year, minutes-to-hours retrieval |
| Glacier Deep Archive | 99.99% | 180 days | Per-GB + retrieval time | Compliance, 12-hour retrieval |
3.2 Lifecycle Policies
Lifecycle policies automatically transition data to lower-cost storage classes or delete it.
{
"Rules": [
{
"ID": "ArchiveAndDelete",
"Status": "Enabled",
"Filter": {
"Prefix": "logs/"
},
"Transitions": [
{
"Days": 30,
"StorageClass": "STANDARD_IA"
},
{
"Days": 90,
"StorageClass": "GLACIER"
}
],
"Expiration": {
"Days": 365
}
}
]
}
3.3 Versioning and Replication
Versioning preserves every change to an object. You can restore previous versions even if objects are accidentally deleted or overwritten.
# Enable versioning
aws s3api put-bucket-versioning \
--bucket my-bucket \
--versioning-configuration Status=Enabled
# List object versions
aws s3api list-object-versions \
--bucket my-bucket \
--prefix config.json
Cross-Region Replication (CRR) and Same-Region Replication (SRR):
- CRR: Automatic replication to another Region for disaster recovery and compliance
- SRR: Log aggregation, data synchronization between dev/prod environments
3.4 Presigned URLs and Event Notifications
Presigned URLs generate temporary URLs that allow unauthenticated access to S3 objects.
import boto3
s3_client = boto3.client('s3')
# Generate a presigned download URL (valid for 1 hour)
url = s3_client.generate_presigned_url(
'get_object',
Params={
'Bucket': 'my-bucket',
'Key': 'reports/annual-2025.pdf'
},
ExpiresIn=3600
)
print(f"Download URL: {url}")
S3 Event Notifications send events like object creation or deletion to Lambda, SQS, or SNS.
# Event notification configuration (CloudFormation)
S3Bucket:
Type: AWS::S3::Bucket
Properties:
NotificationConfiguration:
LambdaConfigurations:
- Event: 's3:ObjectCreated:*'
Filter:
S3Key:
Rules:
- Name: prefix
Value: uploads/
Function: !GetAtt ProcessingFunction.Arn
3.5 S3 Select and Transfer Acceleration
- S3 Select: Extract specific data from objects using SQL queries. Supports CSV, JSON, Parquet
- S3 Transfer Acceleration: Leverages CloudFront Edge Locations to speed up long-distance uploads
3.6 Static Website Hosting
S3 can host static websites directly.
# Configure bucket as static website
aws s3 website s3://my-website-bucket/ \
--index-document index.html \
--error-document error.html
# Sync website files
aws s3 sync ./build/ s3://my-website-bucket/ \
--delete \
--cache-control "max-age=31536000"
4. VPC (Virtual Private Cloud)
VPC enables you to create a logically isolated virtual network within the AWS cloud.
4.1 CIDR Notation and Subnets
CIDR (Classless Inter-Domain Routing) defines IP address ranges.
10.0.0.0/16 → 65,536 IPs (10.0.0.0 - 10.0.255.255)
10.0.1.0/24 → 256 IPs (10.0.1.0 - 10.0.1.255)
10.0.1.0/28 → 16 IPs (10.0.1.0 - 10.0.1.15)
Public Subnet vs Private Subnet:
- Public Subnet: Subnet with a route to an Internet Gateway. Hosts web servers, load balancers
- Private Subnet: Subnet without direct internet access. Hosts databases, application servers
4.2 3-Tier Architecture Design
┌─────────────────────────────────────────────────────────┐
│ VPC: 10.0.0.0/16 │
│ │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ Public Subnet │ │ Public Subnet │ │
│ │ 10.0.1.0/24 │ │ 10.0.2.0/24 │ │
│ │ (AZ-a) │ │ (AZ-b) │ │
│ │ │ │ │ │
│ │ ┌──────────────┐ │ │ ┌──────────────┐ │ │
│ │ │ ALB / NAT GW │ │ │ │ ALB / NAT GW │ │ │
│ │ └──────────────┘ │ │ └──────────────┘ │ │
│ └────────────────────┘ └────────────────────┘ │
│ │ │ │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ Private Subnet │ │ Private Subnet │ │
│ │ (App) 10.0.3.0/24 │ │ (App) 10.0.4.0/24 │ │
│ │ │ │ │ │
│ │ ┌──────────────┐ │ │ ┌──────────────┐ │ │
│ │ │ EC2 / ECS │ │ │ │ EC2 / ECS │ │ │
│ │ └──────────────┘ │ │ └──────────────┘ │ │
│ └────────────────────┘ └────────────────────┘ │
│ │ │ │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ Private Subnet │ │ Private Subnet │ │
│ │ (DB) 10.0.5.0/24 │ │ (DB) 10.0.6.0/24 │ │
│ │ │ │ │ │
│ │ ┌──────────────┐ │ │ ┌──────────────┐ │ │
│ │ │ RDS Primary │ │ │ │ RDS Standby │ │ │
│ │ └──────────────┘ │ │ └──────────────┘ │ │
│ └────────────────────┘ └────────────────────┘ │
│ │
│ ┌──────────┐ │
│ │ IGW │ ← Internet Gateway │
│ └──────────┘ │
└─────────────────────────────────────────────────────────┘
4.3 Internet Gateway and NAT Gateway
- Internet Gateway (IGW): A gateway enabling communication between the VPC and the internet
- NAT Gateway: Allows instances in private subnets to access the internet while blocking inbound connections from outside
# Create a NAT Gateway
aws ec2 create-nat-gateway \
--subnet-id subnet-0123456789abcdef0 \
--allocation-id eipalloc-0123456789abcdef0
4.4 Security Groups vs NACLs
| Attribute | Security Group | Network ACL (NACL) |
|---|---|---|
| Scope | Instance (ENI) level | Subnet level |
| State | Stateful (return traffic auto-allowed) | Stateless (explicit rules needed) |
| Rule Type | Allow rules only | Allow + Deny rules |
| Rule Evaluation | All rules evaluated | Evaluated in number order |
| Default Behavior | All outbound allowed, inbound denied | All traffic allowed |
# Create a security group and add rules
aws ec2 create-security-group \
--group-name web-sg \
--description "Web server security group" \
--vpc-id vpc-0123456789abcdef0
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 443 \
--cidr 0.0.0.0/0
4.5 VPC Peering and Transit Gateway
- VPC Peering: Private network connection between two VPCs. Does not support transitive routing (if A-B and B-C are connected, A cannot directly communicate with C)
- Transit Gateway: Connects multiple VPCs and on-premises networks through a central hub. Supports transitive routing
4.6 VPC Endpoints
VPC Endpoints allow access to AWS services without traversing the internet.
| Type | Supported Services | Cost |
|---|---|---|
| Gateway Endpoint | S3, DynamoDB | Free |
| Interface Endpoint | Most AWS services | Hourly + data transfer |
4.7 VPC Flow Logs
VPC Flow Logs capture IP traffic information from network interfaces.
# Flow Log record example
# version account-id interface-id srcaddr dstaddr srcport dstport protocol packets bytes start end action log-status
2 123456789012 eni-abc123 10.0.1.5 52.94.76.1 49761 443 6 12 1024 1625000000 1625000060 ACCEPT OK
5. IAM (Identity and Access Management)
IAM is the service that securely controls access to AWS resources.
5.1 IAM Components
- Users: Entities representing individual people or services
- Groups: Collections of users needing the same permissions
- Roles: Permission sets that AWS services or external users can temporarily assume
- Policies: JSON documents defining permissions
5.2 Policy JSON Structure
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowS3ReadAccess",
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::my-bucket",
"arn:aws:s3:::my-bucket/*"
],
"Condition": {
"IpAddress": {
"aws:SourceIp": "203.0.113.0/24"
}
}
}
]
}
Policy Components:
- Effect:
AlloworDeny - Action: API operations to allow/deny (e.g.,
s3:GetObject) - Resource: ARN of the target resource
- Condition: Conditional application (IP, time, tags, etc.)
5.3 IAM Roles for EC2 (Instance Profiles)
Attaching an IAM role to an EC2 instance enables access to AWS services without access keys.
# Create an instance profile and attach a role
aws iam create-instance-profile \
--instance-profile-name EC2-S3-ReadOnly
aws iam add-role-to-instance-profile \
--instance-profile-name EC2-S3-ReadOnly \
--role-name S3ReadOnlyRole
# Associate the profile with an EC2 instance
aws ec2 associate-iam-instance-profile \
--instance-id i-0123456789abcdef0 \
--iam-instance-profile Name=EC2-S3-ReadOnly
5.4 Cross-Account Access
Use IAM Role Trust Policies to access resources in other AWS accounts.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::111122223333:root"
},
"Action": "sts:AssumeRole"
}
]
}
5.5 IAM Security Best Practices
- Never use root account: Only set up MFA on root and never use it for daily tasks
- Enable MFA: Require multi-factor authentication for all users
- Least privilege principle: Grant only the minimum permissions necessary
- Rotate access keys: Replace access keys every 90 days
- IAM Access Analyzer: Analyze and monitor resources accessible from outside
- Use temporary credentials: Prefer temporary credentials via STS over long-term credentials
6. RDS (Relational Database Service)
RDS is a managed relational database service that automatically handles patching, backups, and failover.
6.1 Supported Engines
| Engine | Latest Version | Characteristics |
|---|---|---|
| Amazon Aurora | MySQL 8.0/PostgreSQL 16 compatible | Commercial DB performance at open-source pricing |
| MySQL | 8.0 | Most popular open-source DB |
| PostgreSQL | 16 | Advanced features, extensibility |
| MariaDB | 10.11 | MySQL compatible, community-driven |
| Oracle | 19c/21c | Enterprise workloads |
| SQL Server | 2022 | Windows-based applications |
6.2 Multi-AZ and Read Replicas
Multi-AZ (High Availability):
┌──────────────────┐ Synchronous ┌──────────────────┐
│ Primary (AZ-a) │ Replication │ Standby (AZ-b) │
│ │ ──────────────── │ │
│ Read + Write │ Auto Failover │ Standby (No access)│
└──────────────────┘ └──────────────────┘
Read Replicas (Read Scaling):
┌──────────────────┐
│ Read Replica 1 │ ← Read-only
┌──▶│ (Same Region) │
│ └──────────────────┘
┌──────────────┤ ┌──────────────────┐
│ Primary │──▶│ Read Replica 2 │ ← Read-only
│ (Read+Write) │ │ (Same Region) │
└──────────────┤ └──────────────────┘
│ ┌──────────────────┐
└──▶│ Read Replica 3 │ ← Cross-Region
│ (Different Region)│
└──────────────────┘
6.3 Aurora Serverless v2
Aurora Serverless v2 automatically adjusts capacity based on workload.
- ACU (Aurora Capacity Unit): Auto-scales within 0.5-128 ACU range
- Per-second billing: Pay only for the ACUs consumed
- Mixed configuration: Combine provisioned and serverless instances in the same cluster
# Create Aurora Serverless v2 cluster
aws rds create-db-cluster \
--db-cluster-identifier my-aurora-cluster \
--engine aurora-postgresql \
--engine-version 16.1 \
--serverless-v2-scaling-configuration MinCapacity=0.5,MaxCapacity=16 \
--master-username admin \
--master-user-password MySecurePassword123
6.4 Automated Backups and Parameter Groups
- Automated Backups: Daily automatic snapshots (retained up to 35 days)
- Point-in-Time Recovery (PITR): Restore to any point within 5-minute granularity
- Parameter Groups: Customize DB engine settings
6.5 RDS Proxy
RDS Proxy manages database connections through connection pooling. Especially useful in serverless environments like Lambda where short-lived connections are common.
Lambda functions ──▶ RDS Proxy ──▶ RDS Instance
(thousands) (connection (few connections)
pooling)
7. Lambda (Serverless Computing)
Lambda is a serverless compute service that runs code without provisioning or managing servers.
7.1 Event-Driven Architecture
Lambda is triggered by events from various AWS services.
┌─────────────┐ ┌──────────┐ ┌─────────────┐
│ API Gateway │────▶│ │────▶│ DynamoDB │
└─────────────┘ │ │ └─────────────┘
│ │
┌─────────────┐ │ Lambda │ ┌─────────────┐
│ S3 Event │────▶│ Function │────▶│ S3 │
└─────────────┘ │ │ └─────────────┘
│ │
┌─────────────┐ │ │ ┌─────────────┐
│ SQS / SNS │────▶│ │────▶│ SQS / SNS │
└─────────────┘ │ │ └─────────────┘
│ │
┌─────────────┐ │ │ ┌─────────────┐
│ EventBridge │────▶│ │────▶│ Step Func. │
└─────────────┘ └──────────┘ └─────────────┘
7.2 Lambda Function Example
import json
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
def lambda_handler(event, context):
"""Lambda function invoked from API Gateway"""
http_method = event['httpMethod']
path = event['path']
if http_method == 'GET':
response = table.scan()
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps(response['Items'], default=str)
}
elif http_method == 'POST':
body = json.loads(event['body'])
table.put_item(Item=body)
return {
'statusCode': 201,
'body': json.dumps({'message': 'Created successfully'})
}
return {
'statusCode': 400,
'body': json.dumps({'message': 'Unsupported method'})
}
7.3 Cold Start Optimization
A cold start occurs when a Lambda function is invoked for the first time or after a long idle period.
Optimization methods:
- Provisioned Concurrency: Pre-warm instances to eliminate cold starts
- Memory size optimization: Increasing memory proportionally increases CPU
- Package size reduction: Remove unnecessary dependencies
- Lambda SnapStart: Snapshot-based initialization for Java functions (up to 10x faster startup)
- Lambda Layers: Separate common libraries into Layers for reuse
# Configure Provisioned Concurrency
aws lambda put-provisioned-concurrency-config \
--function-name my-function \
--qualifier prod \
--provisioned-concurrent-executions 10
7.4 Lambda@Edge
Lambda@Edge runs Lambda functions at CloudFront Edge Locations. Used for A/B testing, header manipulation, URL redirects, and more.
7.5 Pricing Model
- Requests: 1 million free per month, then approximately $0.20 per million
- Duration: Charged per GB-second (memory x execution time)
- Provisioned Concurrency: Additional cost for provisioned capacity
8. DynamoDB
DynamoDB is a fully managed NoSQL database delivering consistent single-digit millisecond response times.
8.1 Data Model
┌─────────────────────────────────────────────┐
│ Table: Orders │
│ │
│ Partition Key: userId (String) │
│ Sort Key: orderDate (String) │
│ │
│ ┌──────────┬────────────┬────────┬────────┐│
│ │ userId │ orderDate │ total │ status ││
│ ├──────────┼────────────┼────────┼────────┤│
│ │ user-001 │ 2025-01-15 │ 29900 │ shipped││
│ │ user-001 │ 2025-03-20 │ 15000 │ pending││
│ │ user-002 │ 2025-02-10 │ 89000 │ delivered│
│ └──────────┴────────────┴────────┴────────┘│
│ │
│ GSI: StatusIndex │
│ Partition Key: status │
│ Sort Key: orderDate │
└─────────────────────────────────────────────┘
Indexes:
- GSI (Global Secondary Index): Query using different partition and sort keys
- LSI (Local Secondary Index): Same partition key, different sort key (can only be added at table creation)
8.2 Capacity Modes
| Mode | Characteristics | Best For |
|---|---|---|
| On-Demand | Auto-scaling, pay-per-use | Unpredictable traffic |
| Provisioned | Pre-set RCU/WCU, Auto Scaling available | Predictable traffic, cost savings |
8.3 DynamoDB Streams and TTL
- DynamoDB Streams: Captures table changes in real-time. Process events using Lambda triggers
- TTL (Time to Live): Set expiration time to automatically delete stale items
8.4 Single-Table Design Patterns
In DynamoDB, storing multiple entity types in a single table is the recommended pattern.
PK | SK | Data
------------|-----------------|------------------
USER#001 | PROFILE | name, email, ...
USER#001 | ORDER#2025-001 | total, status, ...
USER#001 | ORDER#2025-002 | total, status, ...
ORG#ABC | METADATA | orgName, plan, ...
ORG#ABC | MEMBER#001 | role, joinedAt, ...
9. CloudFront (CDN)
CloudFront is AWS's Content Delivery Network service, caching content at Edge Locations worldwide for fast delivery.
9.1 Distribution Configuration
User ──▶ CloudFront Edge ──▶ Origin
│ │
Cache hit Cache miss
Return immediately Fetch from origin
Origin types:
- S3 bucket (static content)
- ALB / EC2 (dynamic content)
- API Gateway (APIs)
- Custom origin (on-premises servers)
9.2 Cache Policies and Origin Shield
Cache Policy: Defines which elements (headers, query strings, cookies) to include in the cache key.
Origin Shield: Adds an additional caching layer in front of the origin to reduce origin load.
9.3 Lambda@Edge vs CloudFront Functions
| Attribute | Lambda@Edge | CloudFront Functions |
|---|---|---|
| Execution Location | Regional Edge Cache | Edge Location |
| Max Execution Time | 5-30 seconds | 1ms |
| Memory | 128-10,240 MB | 2 MB |
| Network Access | Yes | No |
| Cost | Relatively higher | Very cheap |
| Use Cases | A/B testing, authentication | URL rewrites, header manipulation |
10. Container Services
10.1 ECS (Elastic Container Service)
ECS is an orchestration service for running and managing Docker containers.
Fargate vs EC2 Launch Types:
| Attribute | Fargate | EC2 |
|---|---|---|
| Infrastructure Management | AWS manages | User manages |
| Pricing | vCPU + memory based | EC2 instance costs |
| Scaling | Task-level | Instance + task level |
| GPU Support | No | Yes |
| Best For | Simple operations | GPU, large-scale cost optimization |
10.2 EKS (Elastic Kubernetes Service)
EKS is a managed Kubernetes service. AWS manages the control plane, and worker nodes can run on EC2 or Fargate.
10.3 ECR (Elastic Container Registry)
ECR is a private container registry for storing Docker images.
# Push an image to ECR
aws ecr get-login-password --region us-east-1 | \
docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com
docker tag my-app:latest 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:latest
docker push 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:latest
11. Other Key Services
11.1 Messaging Services
SQS (Simple Queue Service):
- Standard Queue: Unlimited throughput, at-least-once delivery (no ordering guarantee)
- FIFO Queue: Exactly-once delivery, ordering guaranteed (3,000 messages/second)
SNS (Simple Notification Service):
- Pub/Sub messaging model
- Simultaneous notifications to multiple subscribers (fan-out pattern)
EventBridge:
- Serverless event bus for event-driven architectures
- Event pattern matching, schedule-based triggers
- Integration with 100+ AWS services and SaaS applications
11.2 Step Functions
Step Functions is an orchestration service that combines multiple AWS services into visual workflows.
{
"Comment": "Order processing workflow",
"StartAt": "ValidateOrder",
"States": {
"ValidateOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:validate",
"Next": "ProcessPayment"
},
"ProcessPayment": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:payment",
"Next": "ShipOrder",
"Catch": [
{
"ErrorEquals": ["PaymentFailed"],
"Next": "NotifyFailure"
}
]
},
"ShipOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:ship",
"End": true
},
"NotifyFailure": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:notify",
"End": true
}
}
}
11.3 Monitoring and Auditing
CloudWatch:
- Metric collection and dashboards
- Log groups and Log Insights
- Alarms and automated response actions
CloudTrail:
- Records all API calls
- Security auditing and compliance
- 90-day event history stored by default
11.4 Route 53
Route 53 is AWS's managed DNS service.
Routing Policies:
| Policy | Description |
|---|---|
| Simple | Route to a single resource |
| Weighted | Distribute traffic based on weights |
| Latency | Route to the Region with lowest latency |
| Failover | Switch to backup resource on failure |
| Geolocation | Route based on user location |
| Multi-Value | Return multiple healthy resources |
12. Cost Optimization Strategies
12.1 Instance Optimization
- Right-sizing: Use AWS Compute Optimizer to optimize instance sizes
- Reserved Instances: Save up to 72% with 1-year/3-year reservations for steady workloads
- Spot Instances: Save up to 90% for interruptible workloads
- Savings Plans: Flexible discounts through compute usage commitments
12.2 Storage Optimization
- Automate archiving with S3 lifecycle policies
- Optimize EBS volume types (switching from gp2 to gp3 saves up to 20%)
- Clean up unused EBS snapshots and volumes
12.3 Cost Management Tools
| Tool | Function |
|---|---|
| Cost Explorer | Cost analysis and forecasting |
| Budgets | Budget setting and alerts |
| Cost Anomaly Detection | Automatic detection of abnormal spending |
| Trusted Advisor | Cost-saving recommendations |
12.4 Tagging Strategy
Apply consistent tagging to all resources to track costs by team, project, and environment.
# Required tags example
aws ec2 create-tags \
--resources i-0123456789abcdef0 \
--tags \
Key=Environment,Value=Production \
Key=Team,Value=Backend \
Key=Project,Value=UserService \
Key=CostCenter,Value=CC-1234
12.5 Well-Architected Framework
The six pillars of the AWS Well-Architected Framework:
- Operational Excellence: Automation, IaC, observability
- Security: IAM, encryption, network security
- Reliability: Multi-AZ, automatic recovery, disaster recovery
- Performance Efficiency: Appropriate resource selection, monitoring
- Cost Optimization: Pay only for what you use, reservations
- Sustainability: Energy efficiency, resource optimization
13. Quiz
Test your knowledge with the following questions.
Q1. Which S3 feature should you use to automatically move objects to Standard-IA after 30 days, to Glacier after 90 days, and delete them after 365 days?
Answer: S3 Lifecycle Policy
Lifecycle policies use Transition rules to automatically change storage classes and Expiration rules to delete objects. This can significantly reduce costs.
Q2. Which feature completely eliminates Lambda cold starts?
Answer: Provisioned Concurrency
Provisioned Concurrency keeps Lambda execution environments pre-initialized, completely eliminating cold starts. However, it incurs additional costs for provisioned capacity.
Q3. Which service allows instances in a private subnet to access the internet while blocking inbound connections from outside?
Answer: NAT Gateway
A NAT Gateway enables instances in private subnets to send outbound internet traffic while blocking inbound connections from the internet. NAT Gateways must be placed in a public subnet.
Q4. Which DynamoDB index should you use to efficiently query by a non-key attribute?
Answer: GSI (Global Secondary Index)
A GSI allows efficient queries using attributes other than the table's partition key and sort key. GSIs can be added after table creation.
Q5. What is the difference between Multi-AZ RDS and Read Replicas?
Answer:
- Multi-AZ: For high availability (HA). Synchronous replication, automatic failover. Standby is not accessible for reads.
- Read Replicas: For read scaling. Asynchronous replication. Accessible as read-only. Supports cross-Region replication.
Multi-AZ minimizes downtime by automatically switching to the standby instance during failures, while Read Replicas improve performance by distributing read traffic.
References
- AWS Official Documentation
- AWS Well-Architected Framework
- AWS Cost Optimization Guide
- AWS Solutions Library
- AWS re:Invent 2024/2025 Sessions
- AWS Skill Builder
- AWS Architecture Blog
- Amazon Aurora User Guide
- AWS Lambda Developer Guide
- VPC Networking Best Practices
- DynamoDB Developer Guide
- AWS Pricing Calculator
- AWS Serverless Application Model (SAM)