AWS - SQS (Simple Queue Service)

Dragon_Tack·2025년 1월 9일
post-thumbnail

나날히 성장하는 프로젝트에 있어서 많은 트래픽이 들어올때마다 조마조마 했던 기억이있다.

EC2 인스턴스 사용량도 증가하고, RDS 사용량도 증가함에 따라 인스턴스를 더 띄우거나 로드밸런서를 붙여하는 상황이 오기전에 메세지 작업으로 붙여놓은다면 편히 잘 수 있을까?
대기열에 순서를 맥여서 안정적이게 순차적으로 처리를 해보는 방법에 좋은 예시인것 같다.

인스턴스가 죽더라도 너네는 꼭 임무를 완수해야한다...!

1. sendMessage()

export class AwsSqsMessage {
  action: string;
  payload: {
    [key: string]: any;
  };
}
async sendMessage(queueUrl: string, messageBody: string | AwsSqsMessage) {
   try {
     const command = new SendMessageCommand({
       QueueUrl: queueUrl,
       MessageBody:
         typeof messageBody === 'string'
           ? messageBody
           : JSON.stringify(messageBody),
     });
     const response = await this.sqsClient.send(command);
     return response.MessageId ?? '';
   } catch (error) {
     throw error;
   }
 }

2. polling()

  async handler(message: Message) {
    try {
      const parsed = JSON.parse(message.Body);
      const body = plainToInstance(NotificationSqsMessageDto, parsed);
      if (!body) return;
      const { action, payload } = body;
      switch (action) {
        case notificationSqsMessageActionTypeCodes.SEND_NOTIFICATION:
          await this.notificationSqsPollerHandlerService.sendNotification(
            payload,
          );
          return;
        default:
          return;
      }
    } catch (error) {
      Promise.reject(error);
    }
  }

메세징에 action, Payload값을 사전에 정의한데로 전송하면 서버에서 실행이 된다.

분산처리 시스템에서 알맞는 구조인것 같아 internal 통신을 굳이 하지 않더라도, 안전하게 메세지난 이후에 안정적으로 메세지 서비스를 수행해낸다.

profile
고민의 흔적을 늘여놓는 공간

0개의 댓글