놓친 비행에서 미션까지: AWS에서 24시간 알림 서비스 구축

발행: (2025년 11월 30일 오전 06:19 GMT+9)
5 min read
원문: Dev.to

Source: Dev.to

🛠️ 스택

  • 데이터: 약속을 저장하는 DynamoDB 테이블 (Name, Date, Time).
  • 컴퓨트: AWS Lambda가 테이블을 스캔하여 알림이 필요한 약속을 판단합니다.
  • 알림: Amazon SNS가 이메일/SMS 알림을 발송합니다.

단계별 안내

1. DynamoDB 테이블 생성

속성
테이블 이름Appointment
기본 키Partition key = Name (String)
속성Name – 예: “Dentist Visit”
Date – ISO 문자열, 예: 2025-12-29
Time – 선택 사항, 24시간 형식 (HH:mm)

필요에 따라 사용자별 알림을 위해 추가 속성(예: UserEmail)을 추가할 수 있습니다.

2. SNS 토픽 생성 및 구독

  1. Amazon SNSTopicsCreate topic을 엽니다.
  2. Topic 이름: AppointmentReminders (Standard).
  3. Topic ARN을 복사합니다 – Lambda 코드에서 필요합니다.
  4. 구독 추가:
    • 프로토콜: Email (또는 SMS).
    • 엔드포인트: 이메일 주소(또는 전화번호).
  5. AWS에서 보낸 링크를 통해 구독을 확인합니다.

3. Lambda 함수 생성 (Node.js)

구성

  • Runtime: Node.js 18.x
  • Handler: index.handler
  • Memory / Timeout: 128 MB, 30 seconds (필요에 따라 조정)

index.js

// index.js
const { DynamoDBClient, ScanCommand } = require("@aws-sdk/client-dynamodb");
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

// Environment variables (set in Lambda console)
const TABLE_NAME = process.env.APPOINTMENT_TABLE;
const SNS_TOPIC_ARN = process.env.SNS_TOPIC_ARN;

const ddb = new DynamoDBClient({});
const sns = new SNSClient({});

exports.handler = async () => {
  // 1️⃣ Scan the Appointment table
  const scanParams = {
    TableName: TABLE_NAME,
    ProjectionExpression: "Name, #d, #t, Email",
    ExpressionAttributeNames: {
      "#d": "Date",
      "#t": "Time"
    }
  };

  const data = await ddb.send(new ScanCommand(scanParams));

  // 2️⃣ Determine which items are within the next 24 h
  const now = new Date();
  const next24h = new Date(now.getTime() + 24 * 60 * 60 * 1000);

  const reminders = data.Items.filter(item => {
    const dateStr = item.Date.S;               // e.g. "2025-12-29"
    const timeStr = item.Time?.S || "00:00";   // optional, default midnight
    const apptDate = new Date(`${dateStr}T${timeStr}:00Z`);
    return apptDate > now && apptDate <= next24h;
  });

  // 3️⃣ Publish a reminder for each upcoming appointment
  for (const appt of reminders) {
    const message = `Reminder: ${appt.Name.S} on ${appt.Date.S} at ${appt.Time?.S || "00:00"}.`;
    const publishParams = {
      TopicArn: SNS_TOPIC_ARN,
      Message: message,
      Subject: "24‑hour Appointment Reminder",
      MessageAttributes: {
        "email": {
          DataType: "String",
          StringValue: appt.Email?.S || ""
        }
      }
    };
    await sns.send(new PublishCommand(publishParams));
  }

  return {
    statusCode: 200,
    body: `Sent ${reminders.length} reminder(s).`
  };
};

Lambda 콘솔에 설정할 환경 변수

변수
APPOINTMENT_TABLEAppointment
SNS_TOPIC_ARNARN of the AppointmentReminders topic

4. Lambda용 IAM 권한

Lambda 실행 역할에 다음을 허용하는 인라인 정책(또는 관리형 정책)을 연결합니다:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:Scan",
        "dynamodb:Query",
        "dynamodb:GetItem"
      ],
      "Resource": "arn:aws:dynamodb:*:*:table/Appointment"
    },
    {
      "Effect": "Allow",
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:*:*:AppointmentReminders"
    }
  ]
}

5. DynamoDB에 테스트 아이템 추가

이름날짜시간이메일
Dentist Visit2025-12-2909:00your.email@example.com

콘솔이나 AWS CLI를 통해 아이템을 추가할 수 있습니다:

aws dynamodb put-item \
  --table-name Appointment \
  --item '{"Name":{"S":"Dentist Visit"},"Date":{"S":"2025-12-29"},"Time":{"S":"09:00"},"Email":{"S":"your.email@example.com"}}'

6. Lambda 테스트

  1. Lambda 콘솔에서 Test를 클릭하고 간단한 이벤트를 생성합니다 (함수는 페이로드를 사용하지 않습니다).
  2. 테스트를 실행합니다.
  3. 이메일(또는 SMS)을 확인합니다 – 다음과 같은 메시지를 받아야 합니다:
Subject: 24‑hour Appointment Reminder
Message: Reminder: Dentist Visit on 2025-12-29 at 09:00.

이메일을 확인하면 엔드‑투‑엔드 흐름이 정상적으로 동작하는 것입니다.

🚀 배운 점

  • 잊어버리는 것은 쉽지만, 시스템은 그렇지 않습니다. 작은 서버리스 스택으로 신뢰성 있게 알림을 받을 수 있습니다.
  • 24시간 타이밍은 방해가 되지 않으면서 충분한 준비 시간을 제공합니다.
  • 대규모 플랫폼이 필요 없습니다—DynamoDB 테이블, Lambda 함수, SNS 토픽, 그리고 하루에 한 번 Lambda를 실행하는 스케줄 트리거(예: CloudWatch Events / EventBridge)만 있으면 됩니다.
  • 이 프로젝트를 구축하면서 핵심 DevOps / Cloud Engineering 기술을 다졌습니다: IAM 최소 권한 정책, Lambda 개발, DynamoDB 데이터 모델링, SNS 알림.

이것이 전체 알림 서비스입니다—단순하고 저렴하며 효과적입니다. 즐거운 개발 되세요!

Back to Blog

관련 글

더 보기 »