AWS SAA-C03 Message 관련 패턴
AWS SAA-C03 Message 관련 패턴 — #개발자의도구들 #AWSSAA #AWSmessage #AWSSQS #AWSSNS * AWS SAA 도전기 목록...
#개발자의도구들 #AWSSAA #AWSmessage #AWSSQS #AWSSNS
\* AWS SAA 도전기 목록: https://blog.naver.com/jword\_/224028873217
Fan-out pattern
출처: Exmptopic
핵심 요구사항
- 애플리케이션: 들어오는 메시지 수집
- 소비자: 수십 개의 애플리케이션과 마이크로서비스
- 메시지 양: 급격하게 변동 (때로는 초당 100,000개까지 급증)
- 목표:
- ✅ 솔루션 디커플링 (Decouple)
- ✅ 확장성 증가 (Scalability)
보기
A. Persist the messages to Amazon Kinesis Data Analytics. Configure the consumer applications to read and process the messages.
B. Deploy the ingestion application on Amazon EC2 instances in an Auto Scaling group to scale the number of EC2 instances based on CPU metrics.
C. Write the messages to Amazon Kinesis Data Streams with a single shard. Use an AWS Lambda function to preprocess messages and store them in Amazon DynamoDB. Configure the consumer applications to read from DynamoDB to process the messages.
D. Publish the messages to an Amazon Simple Notification Service (Amazon SNS) topic with multiple Amazon Simple Queue Service (Amazon SOS) subscriptions. Configure the consumer applications to process the messages from the queues.
문제 풀이
✅ FanOut 패턴
:하나의 메세지 → 여러 소비자가 처리하는 패턴이다.
👉 Amazon SNS 토픽에 메세지 발행 → 여러 SQS 큐 구독 → 각 소비자가 독립적으로 처리
📌 아키텍처
┌─────────────────────────────────────────────────────────┐
│ Ingestion Application │
│ (메시지 수신 애플리케이션) │
└──────────────────────┬──────────────────────────────────┘
│
│ Publish (초당 100,000 메시지)
▼
┌──────────────────────┐
│ Amazon SNS Topic │
│ (메시지 발행) │
└──────────┬───────────┘
│
┏━━━━━━━━━━━━━┻━━━━━━━━━━━━━┓
┃ Fan-out Pattern ┃
┃ (1 → 다수 배포) ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
│
┌──────────────────┼──────────────────┐
│ │ │
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│SQS Queue│ │SQS Queue│ ... │SQS Queue│
│ #1 │ │ #2 │ │ #N │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│Consumer │ │Consumer │ │Consumer │
│ App 1 │ │ App 2 │ ... │ App N │
└─────────┘ └─────────┘ └─────────┘
📜 상세 설명
- 완전한 디커플링
- 각 소비자 독립적 처리
- 무제한 확장성
- SNS 처리량: 초당 수백만 메세지, 자동확장, 무제한
- SQS 처리량:
- 표준 큐: 무제한 TPS
- 각 큐는 독립적으로 확장
- 버퍼링
"메세지를 안정적으로 처리하기 위해서" → SQS를 Buffer 느낌으로 사용하면 된다.
⚒️ 실제 구현
// Step 1: SNS 토픽 생성
aws sns create-topic --name message-ingestion-topic
// Step 2: SQS queue 생성(각 소비자용)
aws sqs create-queue --queue-name consumer-1
aws sqs create-queue --queue-name consumer-2
aws sqs create-queue --queue-name consumer-3
// Step 3: SNS 구독설정
aws sns subscribe \
--topic-arn arn:aws:sns:region:account:message-ingestion-topic \
--protocol sqs \
--notification-endpoint arn:aws:sqs:region:account:consumer-1
aws sns subscribe \
--topic-arn arn:aws:sns:region:account:message-ingestion-topic \
--protocol sqs \
--notification-endpoint arn:aws:sqs:region:account:consumer-2
aws sns subscribe \
--topic-arn arn:aws:sns:region:account:message-ingestion-topic \
--protocol sqs \
--notification-endpoint arn:aws:sqs:region:account:consumer-3
// Step 4: SQS 정책 설정
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "sns.amazonaws.com"
},
"Action": "sqs:SendMessage",
"Resource": "arn:aws:sqs:region:account:consumer-1-queue",
"Condition": {
"ArnEquals": {
"aws:SourceArn": "arn:aws:sns:region:account:message-ingestion-topic"
}
}
}
]
}
// Step 5: Ingestion Application Code (Producer)
import boto3
import json
sns_client = boto3.client('sns')
TOPIC_ARN = 'arn:aws:sns:region:account:message-ingestion-topic'
def publish_message(message_data):
"""메시지를 SNS에 발행"""
response = sns_client.publish(
TopicArn=TOPIC_ARN,
Message=json.dumps(message_data),
MessageAttributes={
'timestamp': {
'DataType': 'String',
'StringValue': str(time.time())
}
}
)
return response['MessageId']
# 대량 메시지 발행
for i in range(100000):
message = {
'id': i,
'data': 'message content',
'timestamp': time.time()
}
publish_message(message)
// Step 6: Consumer Application
import boto3
import json
sqs_client = boto3.client('sqs')
QUEUE_URL = 'https://sqs.region.amazonaws.com/account/consumer-1-queue'
def process_messages():
"""SQS에서 메시지 수신 및 처리"""
while True:
response = sqs_client.receive_message(
QueueUrl=QUEUE_URL,
MaxNumberOfMessages=10, # 배치 처리
WaitTimeSeconds=20, # Long polling
MessageAttributeNames=['All']
)
if 'Messages' in response:
for message in response['Messages']:
try:
# SNS 메시지 파싱
sns_message = json.loads(message['Body'])
actual_message = json.loads(sns_message['Message'])
# 비즈니스 로직 처리
process_business_logic(actual_message)
# 처리 완료 후 삭제
sqs_client.delete_message(
QueueUrl=QUEUE_URL,
ReceiptHandle=message['ReceiptHandle']
)
except Exception as e:
print(f"Error processing message: {e}")
# 실패 시 DLQ로 이동 (자동)
process_messages()
AWS CLI와 Python을 활용하여 간단한 실습을 진행해볼 수 있다.
- 복습할 때 해보고 정리해보겠습니다.
😵💫비슷한 서비스
Kinesis
- message를 Kenesis Data Anlytics에 저장하고 소비자가 읽기
❌
- Kinensis는 Data 분석을 위한 도구이다.
- 메세지 저장소와 다른 개념
요구 지식 정리