ระดับ 4a · บทที่ 3/5

คิวและอีเวนต์ — SQS, SNS, EventBridge, DLQ และ idempotency

⏱ 55 นาทีลองในAWS Console ↗
ข้อมูลบางส่วนอาจเปลี่ยน — ตรวจสอบก่อนใช้

บทนี้มีข้อมูลที่เปลี่ยนบ่อย (ฟีเจอร์ ราคา ชื่อเมนู) ตรวจกับเว็บทางการก่อนนำไปใช้

เป้าหมาย

แยกระบบออกเป็นชิ้นที่คุยกันผ่านคิว/อีเวนต์ เลือกได้ว่าเมื่อไรใช้ SQS, SNS หรือ EventBridge ตั้ง DLQ ให้ข้อความที่พังไม่หายและไม่วนไม่จบ และเขียน consumer แบบ idempotent เพราะทุกบริการในบทนี้ส่ง "อย่างน้อยหนึ่งครั้ง" (อาจซ้ำ)

ทำไมต้องมีคิว

API รับออเดอร์แล้วเรียกระบบชำระเงิน ส่งอีเมล ตัดสต็อก ต่อกันแบบ sync → ตัวใดตัวหนึ่งช้า/ล่ม ลูกค้ารอหรือพังทั้งสาย ใส่คิวคั่น → API ตอบ 202 Accepted ทันที งานเบื้องหลังทำทีหลัง ทนการล่มชั่วคราว ดูดซับ traffic พุ่ง และ retry ได้เอง

สามบริการ หน้าที่ต่างกัน

SQS SNS EventBridge
รูปแบบ คิว: ผู้รับดึงไปทำ (pull) pub/sub: ส่งต่อให้ทุกผู้ติดตาม (push) event bus: กระจายตาม กฎจับรูปแบบ
ผู้รับต่อข้อความ 1 consumer ต่อข้อความ ทุก subscriber ทุก rule ที่ match
เก็บข้อความรอ ✅ สูงสุด 14 วัน ❌ (ไม่มีคนรับ = หาย ยกเว้นตั้ง DLQ ต่อ subscription) ❌ (มี archive/replay ได้)
กรอง ฝั่ง Lambda ESM filter filter policy ต่อ subscription event pattern ละเอียด (prefix, numeric, exists ...)
เด่น buffer งาน คุมความเร็ว consumer fan-out ง่าย, SMS/อีเมล/มือถือ event จาก AWS เอง + SaaS, ตารางเวลา (Scheduler), schema

แพทเทิร์นที่ใช้บ่อย: ผู้ผลิตส่ง event ไป EventBridge (หรือ SNS) → แต่ละระบบมี SQS ของตัวเอง เป็นปลายทาง → Lambda ดึงจากคิว · ได้ทั้ง fan-out และ buffer/retry ต่อระบบ

SQS ที่ต้องรู้จริง

  • Standard queue: throughput แทบไม่จำกัด, ลำดับไม่รับประกัน, อาจส่งซ้ำ
  • FIFO queue: ลำดับตาม MessageGroupId, กันซ้ำในหน้าต่าง 5 นาที, throughput จำกัดกว่า · ชื่อต้องลงท้าย .fifo
  • Visibility timeout: ข้อความที่ถูกดึงไปจะซ่อนชั่วคราว ถ้าไม่ถูกลบภายในเวลานี้ → กลับมาให้คนอื่นดึงอีก · กับ Lambda ตั้ง อย่างน้อย 6 เท่าของ timeout ฟังก์ชัน
  • DLQ + maxReceiveCount: ข้อความที่ถูกดึงครบ N ครั้งแล้วยังไม่สำเร็จ → ย้ายไป DLQ ไม่วนไม่จบ · DLQ ต้องมีคนดูและมี alarm
  • ข้อความสูงสุด 1 MiB (ใหญ่กว่านั้นเก็บใน S3 แล้วส่ง key)

Lambda + SQS: batch และ partial failure

  • Lambda ดึงเป็น batch (ค่าเริ่มต้น 10) แล้วเรียกฟังก์ชันครั้งเดียว
  • ถ้า throw ทั้ง batch → ทุกข้อความ กลับคิว รวมตัวที่สำเร็จแล้ว → ทำซ้ำ
  • เปิด ReportBatchItemFailures แล้วคืน { batchItemFailures: [{ itemIdentifier: messageId }] } เฉพาะตัวที่พัง → ตัวที่สำเร็จถูกลบ

Idempotency — ทำซ้ำแล้วผลเหมือนทำครั้งเดียว

ข้อความซ้ำมาได้จาก: SQS standard, retry ของ Lambda, ผู้ผลิตส่งซ้ำ, visibility timeout หมดกลางงาน

วิธี ตัวอย่าง
idempotency key + conditional write บันทึก orderId ลง DynamoDB ด้วย attribute_not_exists ถ้าชน = เคยทำแล้ว ข้าม (บท 3a-05)
ทำงานแบบ "ตั้งค่า" แทน "เพิ่มค่า" status = PAID แทน balance = balance - 100
ใช้ key ปลายทางกันซ้ำ ส่ง Idempotency-Key ไปบริการชำระเงิน
Powertools for AWS Lambda utility idempotency ทำให้ครบ (TS/Python/Java/.NET)

ลองเลย 🧪

SQS, EventBridge, Lambda และ DynamoDB on-demand ระดับนี้อยู่ในโควตาฟรี/เศษสตางค์ — เก็บกวาดท้ายบท

export AWS_PROFILE=learn   # profile SSO ที่ตั้งไว้ในระดับ 2
export AWS_REGION=ap-southeast-1
aws sso login
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
mkdir -p queue-lab && cd queue-lab

ทดลอง A — คิวหลัก + DLQ + ตารางกันซ้ำ

DLQ=$(aws sqs create-queue --queue-name lab-orders-dlq --query QueueUrl --output text)
DLQ_ARN=$(aws sqs get-queue-attributes --queue-url $DLQ --attribute-names QueueArn --query Attributes.QueueArn --output text)
cat > q-attrs.json <<EOF
{
  "VisibilityTimeout": "60",
  "RedrivePolicy": "{\"deadLetterTargetArn\":\"$DLQ_ARN\",\"maxReceiveCount\":\"3\"}"
}
EOF
Q=$(aws sqs create-queue --queue-name lab-orders --attributes file://q-attrs.json --query QueueUrl --output text)
Q_ARN=$(aws sqs get-queue-attributes --queue-url $Q --attribute-names QueueArn --query Attributes.QueueArn --output text)

aws dynamodb create-table --table-name lab-processed \
  --attribute-definitions AttributeName=orderId,AttributeType=S \
  --key-schema AttributeName=orderId,KeyType=HASH --billing-mode PAY_PER_REQUEST > /dev/null
aws dynamodb wait table-exists --table-name lab-processed
echo "Q=$Q DLQ=$DLQ Q_ARN=$Q_ARN DLQ_ARN=$DLQ_ARN" | tee ids.txt

ถ้าปิด terminal: cd queue-lab && export AWS_PROFILE=learn AWS_REGION=ap-southeast-1 && export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) && source ids.txt

ทดลอง B — worker แบบ idempotent + partial batch failure

cat > trust.json <<'EOF'
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }] }
EOF
cat > ddb-put.json <<EOF
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow", "Action": "dynamodb:PutItem",
                  "Resource": "arn:aws:dynamodb:$AWS_REGION:$ACCOUNT_ID:table/lab-processed" }] }
EOF
aws iam create-role --role-name lab-worker-role --assume-role-policy-document file://trust.json > /dev/null
aws iam attach-role-policy --role-name lab-worker-role \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaSQSQueueExecutionRole
aws iam put-role-policy --role-name lab-worker-role --policy-name ddb-put --policy-document file://ddb-put.json
sleep 10

cat > index.mjs <<'EOF'
import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb";
const ddb = new DynamoDBClient({});

export const handler = async (event) => {
  const batchItemFailures = [];
  for (const record of event.Records) {
    try {
      const msg = JSON.parse(record.body);
      const order = msg.detail ?? msg;                 // มาจาก EventBridge หรือส่งตรง
      if (order.item === "boom") throw new Error("poison message");
      await ddb.send(new PutItemCommand({
        TableName: process.env.TABLE,
        Item: { orderId: { S: order.orderId }, item: { S: order.item } },
        ConditionExpression: "attribute_not_exists(orderId)",
      }));
      console.log(JSON.stringify({ processed: order.orderId }));
    } catch (err) {
      if (err.name === "ConditionalCheckFailedException") {
        console.log(JSON.stringify({ duplicateSkipped: record.messageId }));
        continue;                                      // ซ้ำ = ถือว่าสำเร็จ
      }
      console.error(JSON.stringify({ failed: record.messageId, error: err.message }));
      batchItemFailures.push({ itemIdentifier: record.messageId });
    }
  }
  return { batchItemFailures };
};
EOF
zip -q fn.zip index.mjs
aws lambda create-function --function-name lab-worker --runtime nodejs24.x --architectures arm64 \
  --handler index.handler --zip-file fileb://fn.zip --timeout 10 --memory-size 256 \
  --environment "Variables={TABLE=lab-processed}" \
  --role arn:aws:iam::$ACCOUNT_ID:role/lab-worker-role > /dev/null
aws lambda wait function-active-v2 --function-name lab-worker
ESM=$(aws lambda create-event-source-mapping --function-name lab-worker --event-source-arn $Q_ARN \
  --batch-size 5 --function-response-types ReportBatchItemFailures --query UUID --output text)
echo "ESM=$ESM" >> ids.txt

ทดลอง C — ส่งข้อความปกติ ซ้ำ และพิษ

aws sqs send-message --queue-url $Q --message-body '{"orderId":"o-1001","item":"latte"}' > /dev/null
aws sqs send-message --queue-url $Q --message-body '{"orderId":"o-1001","item":"latte"}' > /dev/null
aws sqs send-message --queue-url $Q --message-body '{"orderId":"o-1002","item":"boom"}' > /dev/null
sleep 30
aws logs tail /aws/lambda/lab-worker --since 5m --format short | grep -E "processed|duplicate|failed"
aws dynamodb get-item --table-name lab-processed --key '{"orderId":{"S":"o-1001"}}' --query Item.item.S --output text

ผลที่ควรเห็น:

... {"processed":"o-1001"}
... {"duplicateSkipped":"..."}
... {"failed":"...","error":"poison message"}
latte

รอราว 3–4 นาที (visibility 60 วินาที × 3 ครั้ง) แล้วดู DLQ:

aws sqs get-queue-attributes --queue-url $DLQ --attribute-names ApproximateNumberOfMessages \
  --query Attributes.ApproximateNumberOfMessages --output text
aws sqs receive-message --queue-url $DLQ --query 'Messages[0].Body' --output text

ผลที่ควรเห็น:

1
{"orderId":"o-1002","item":"boom"}

→ ข้อความซ้ำไม่ทำให้ข้อมูลเพี้ยน ข้อความพิษถูกลองครบ 3 ครั้งแล้วถูกกักไว้ใน DLQ ไม่วนทำร้ายระบบ · แก้บั๊กแล้วย้ายกลับด้วย aws sqs start-message-move-task --source-arn $DLQ_ARN

ทดลอง D — EventBridge กระจาย event เข้าคิว

cat > queue-policy.json <<EOF
{ "Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"events.amazonaws.com\"},\"Action\":\"sqs:SendMessage\",\"Resource\":\"$Q_ARN\",\"Condition\":{\"ArnEquals\":{\"aws:SourceArn\":\"arn:aws:events:$AWS_REGION:$ACCOUNT_ID:rule/lab-order-placed\"}}}]}" }
EOF
aws sqs set-queue-attributes --queue-url $Q --attributes file://queue-policy.json
aws events put-rule --name lab-order-placed \
  --event-pattern '{"source":["lab.shop"],"detail-type":["OrderPlaced"]}' --query RuleArn --output text
aws events put-targets --rule lab-order-placed --targets "Id=orders-queue,Arn=$Q_ARN"
aws events put-events --entries '[{"Source":"lab.shop","DetailType":"OrderPlaced","Detail":"{\"orderId\":\"o-2001\",\"item\":\"mocha\"}"}]' \
  --query FailedEntryCount --output text
sleep 20
aws dynamodb get-item --table-name lab-processed --key '{"orderId":{"S":"o-2001"}}' --query Item.item.S --output text

ผลที่ควรเห็น:

arn:aws:events:ap-southeast-1:123456789012:rule/lab-order-placed
0
mocha

→ ผู้ส่ง event ไม่รู้เลยว่าใครรับ เพิ่มระบบใหม่แค่เพิ่ม rule + คิวของตัวเอง (choreography — เทียบกับ orchestration ในบท 05)

เก็บกวาด

aws lambda delete-event-source-mapping --uuid $ESM > /dev/null
aws events remove-targets --rule lab-order-placed --ids orders-queue > /dev/null
aws events delete-rule --name lab-order-placed
aws lambda delete-function --function-name lab-worker
aws logs delete-log-group --log-group-name /aws/lambda/lab-worker
aws sqs delete-queue --queue-url $Q
aws sqs delete-queue --queue-url $DLQ
aws dynamodb delete-table --table-name lab-processed > /dev/null
aws iam delete-role-policy --role-name lab-worker-role --policy-name ddb-put
aws iam detach-role-policy --role-name lab-worker-role \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaSQSQueueExecutionRole
aws iam delete-role --role-name lab-worker-role
cd .. && rm -rf queue-lab

กับดักที่เจอบ่อย

อาการ สาเหตุ / แก้
ข้อความถูกประมวลผลซ้ำๆ ทั้งที่ฟังก์ชันสำเร็จ visibility timeout สั้นกว่าเวลาประมวลผล → ตั้ง ≥ 6 เท่าของ timeout ฟังก์ชัน
ข้อความดีถูกทำซ้ำเมื่อมีตัวเดียวพัง throw ทั้ง batch → เปิด ReportBatchItemFailures และคืนเฉพาะตัวที่พัง
ข้อความพิษวนไม่จบ บิลขึ้นเรื่อยๆ ไม่มี DLQ/maxReceiveCount
DLQ มีข้อความค้างเป็นสัปดาห์ไม่มีใครรู้ ไม่มี alarm บน ApproximateNumberOfMessagesVisible ของ DLQ (ระดับ 5a)
EventBridge ส่งเข้าคิวไม่ได้ (FailedInvocations) queue policy ไม่อนุญาต events.amazonaws.com หรือ SourceArn ไม่ตรง
event ไม่ match rule pattern ต้องตรงชนิดข้อมูลและเป็น array เช่น "source": ["lab.shop"]
ยอดเงินถูกตัดสองครั้ง consumer ไม่ idempotent — ใช้ idempotency key + conditional write

สรุปจำง่าย

คิวคั่นระหว่างระบบ ตอบ 202 แล้วทำทีหลัง — SQS = buffer, SNS = fan-out, EventBridge = กระจายตามกฎ — visibility ≥ 6× timeout — DLQ + alarm เสมอ — ReportBatchItemFailures — ทุกอย่างส่ง "อย่างน้อยหนึ่งครั้ง" consumer ต้อง idempotent