เป้าหมาย
สร้าง workflow หลายขั้นที่ ทนพัง: retry เฉพาะ error ชั่วคราว, จับ error แล้วทำขั้นชดเชย (compensation), เห็นทุกขั้นในประวัติการรัน — และตัดสินได้ว่าเมื่อไรใช้ orchestration (Step Functions) เมื่อไรใช้ choreography (อีเวนต์ บท 03)
ปัญหาที่ Step Functions แก้
งาน "รับออเดอร์ → ตัดบัตร → จองสต็อก → ส่งของ → แจ้งลูกค้า" ถ้าเขียนใน Lambda ตัวเดียว:
- เกิน 15 นาทีไม่ได้ ต้องรอคนอนุมัติไม่ได้
- retry/backoff/timeout เขียนเองทุกที่ พังกลางทางไม่รู้ว่าถึงขั้นไหน
- จองสต็อกไม่ได้ → ต้อง คืนเงิน (ชดเชย) เขียนให้ถูกยาก
Step Functions = state machine ที่ AWS รันให้ เก็บสถานะทุกขั้น retry ให้ตามกติกา และแสดงเป็นแผนภาพในคอนโซล
Standard vs Express
| Standard | Express | |
|---|---|---|
| รันได้นานสุด | 1 ปี | 5 นาที |
| การทำงาน | exactly-once ต่อขั้น | at-least-once (async) / at-most-once (sync) |
| ประวัติ | เก็บใน Step Functions ดูย้อนหลังได้ | ส่งไป CloudWatch Logs (ต้องเปิด) |
| คิดเงิน | ต่อ state transition (~$0.025 ต่อ 1,000, ฟรี 4,000/เดือน) | ต่อ request (~$1/ล้าน) + GB-s |
| เหมาะ | ธุรกรรมธุรกิจ, รอคน/รอนาน, งานที่ห้ามทำซ้ำ | งานถี่สูง สั้น เช่น แปลง event ทีละมากๆ |
⚠️ ต้องตรวจสอบ: ราคาของ region ที่ใช้ที่ https://aws.amazon.com/step-functions/pricing/ — workflow ที่วนลูปเยอะแบบ Standard นับ transition ทุกขั้น
ชนิด state ที่ใช้บ่อย
| State | ทำอะไร |
|---|---|
Task |
เรียกงาน: Lambda, หรือเรียก AWS API ตรง (DynamoDB, SQS, SNS, ECS ...) ได้กว่าร้อยบริการโดยไม่ต้องมี Lambda |
Choice |
แยกทางตามค่าใน input |
Parallel / Map |
ทำหลายสาขาพร้อมกัน / วนทำกับทุกรายการในลิสต์ (Distributed Map ทำได้หลักล้านรายการ) |
Wait |
รอเป็นวินาทีหรือถึงเวลาที่กำหนด (ไม่เสียเงินระหว่างรอใน Standard) |
Pass / Succeed / Fail |
ส่งต่อข้อมูล / จบสำเร็จ / จบแบบล้มเหลวพร้อมชื่อ error |
ภาษาแปลงข้อมูล: แบบเดิม JSONPath (InputPath, Parameters, ResultPath) หรือแบบใหม่ JSONata ("QueryLanguage": "JSONata" ใช้ Arguments/Output และนิพจน์ {% ... %}) — บทนี้ใช้ JSONPath เพราะตัวอย่างในโลกยังเยอะกว่า
Retry และ Catch — หัวใจของความทนทาน
"Retry": [
{ "ErrorEquals": ["TransientError", "Lambda.TooManyRequestsException"],
"IntervalSeconds": 1, "BackoffRate": 2, "MaxAttempts": 3, "JitterStrategy": "FULL" }
],
"Catch": [
{ "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "Compensate" }
]- Retry เฉพาะ error ชั่วคราว (timeout, throttle, ระบบปลายทางล่ม) — error จากข้อมูลผิดลองกี่รอบก็ผิด
- backoff + jitter กันทุก execution ยิงซ้ำพร้อมกัน
- Catch ส่งไปขั้นชดเชย/แจ้งคน โดยเก็บรายละเอียด error ไว้ใน
ResultPathไม่ทับ input เดิม - งานที่ retry ได้ต้อง idempotent (บท 03) — retry แปลว่าอาจทำซ้ำ
Orchestration vs Choreography
| Orchestration (Step Functions) | Choreography (EventBridge/SNS/SQS) | |
|---|---|---|
| ใครคุม | มีผู้คุมกลางรู้ทุกขั้น | แต่ละระบบฟัง event แล้วทำของตัวเอง |
| มองเห็น | เห็นทั้ง flow และสถานะต่อรายการในที่เดียว | ต้องรวม log/trace จากหลายที่ |
| coupling | ผู้คุมรู้จักทุกขั้น | ระบบไม่รู้จักกัน เพิ่มผู้ฟังใหม่ง่าย |
| เหมาะ | ธุรกรรมหลายขั้นที่ต้องสำเร็จครบหรือชดเชย (saga), มีคนอนุมัติ | แจ้งข่าวว่า "เกิดอะไรขึ้น" ให้หลายระบบที่ต่างคนต่างทำ |
ระบบจริงใช้ ทั้งสอง: ภายในโดเมนใช้ Step Functions คุมธุรกรรม เมื่อเสร็จส่ง event OrderCompleted ไป EventBridge ให้ระบบอื่นฟัง
ลองเลย 🧪
Standard workflow ไม่กี่ execution อยู่ในโควตาฟรี 4,000 transition/เดือน
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 sfn-lab && cd sfn-labทดลอง A — Lambda "จองสต็อก" ที่พังได้ตามสั่ง
permission set ต้องสร้าง IAM role ได้ (AdministratorAccess จากระดับ 2 — PowerUserAccess ทำไม่ได้) · แล็บนี้สร้าง 2 role
cat > trust-lambda.json <<'EOF'
{ "Version": "2012-10-17",
"Statement": [{ "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }] }
EOF
aws iam create-role --role-name lab-flaky-role --assume-role-policy-document file://trust-lambda.json > /dev/null
aws iam attach-role-policy --role-name lab-flaky-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
sleep 10
cat > index.mjs <<'EOF'
class TransientError extends Error { constructor(m) { super(m); this.name = "TransientError"; } }
export const handler = async (event) => {
console.log(JSON.stringify({ orderId: event.orderId, mode: event.mode }));
if (event.mode === "broken") throw new TransientError("คลังสินค้าไม่ตอบ");
return { reservationId: `rsv-${event.orderId}`, items: event.items ?? 1 };
};
EOF
zip -q fn.zip index.mjs
aws lambda create-function --function-name lab-flaky --runtime nodejs24.x --architectures arm64 \
--handler index.handler --zip-file fileb://fn.zip --timeout 5 \
--role arn:aws:iam::$ACCOUNT_ID:role/lab-flaky-role > /dev/null
aws lambda wait function-active-v2 --function-name lab-flakyทดลอง B — state machine ที่มี Choice, Retry, Catch และขั้นชดเชย
cat > trust-sfn.json <<'EOF'
{ "Version": "2012-10-17",
"Statement": [{ "Effect": "Allow", "Principal": { "Service": "states.amazonaws.com" }, "Action": "sts:AssumeRole" }] }
EOF
cat > invoke.json <<EOF
{ "Version": "2012-10-17",
"Statement": [{ "Effect": "Allow", "Action": "lambda:InvokeFunction",
"Resource": ["arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:lab-flaky",
"arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:lab-flaky:*"] }] }
EOF
aws iam create-role --role-name lab-sfn-role --assume-role-policy-document file://trust-sfn.json > /dev/null
aws iam put-role-policy --role-name lab-sfn-role --policy-name invoke-flaky --policy-document file://invoke.json
sleep 10
cat > flow.json <<EOF
{
"Comment": "ตรวจออเดอร์ จองสต็อก และชดเชยเมื่อพัง",
"StartAt": "Validate",
"States": {
"Validate": {
"Type": "Choice",
"Choices": [{ "Variable": "\$.amount", "NumericGreaterThan": 0, "Next": "Reserve" }],
"Default": "Rejected"
},
"Reserve": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": { "FunctionName": "arn:aws:lambda:$AWS_REGION:$ACCOUNT_ID:function:lab-flaky", "Payload.\$": "\$" },
"ResultSelector": { "reservation.\$": "\$.Payload" },
"ResultPath": "\$.reserve",
"Retry": [{ "ErrorEquals": ["TransientError"], "IntervalSeconds": 1, "BackoffRate": 2, "MaxAttempts": 3 }],
"Catch": [{ "ErrorEquals": ["States.ALL"], "ResultPath": "\$.error", "Next": "Compensate" }],
"Next": "Done"
},
"Compensate": {
"Type": "Pass",
"Result": "คืนเงินและแจ้งลูกค้าแล้ว",
"ResultPath": "\$.compensation",
"Next": "ReserveFailed"
},
"ReserveFailed": { "Type": "Fail", "Error": "ReserveFailed", "Cause": "จองสต็อกไม่สำเร็จหลัง retry" },
"Rejected": { "Type": "Fail", "Error": "InvalidOrder", "Cause": "amount ต้องมากกว่า 0" },
"Done": { "Type": "Succeed" }
}
}
EOF
SM=$(aws stepfunctions create-state-machine --name lab-order-flow --type STANDARD \
--definition file://flow.json --role-arn arn:aws:iam::$ACCOUNT_ID:role/lab-sfn-role \
--query stateMachineArn --output text)
echo "SM=$SM" | tee ids.txt # ปิด terminal: cd sfn-lab && export AWS_PROFILE=learn AWS_REGION=ap-southeast-1 && source ids.txtผลที่ควรเห็น:
SM=arn:aws:states:ap-southeast-1:123456789012:stateMachine:lab-order-flowทดลอง C — รันสามกรณี: สำเร็จ, ข้อมูลผิด, ระบบปลายทางล่ม
run() {
ARN=$(aws stepfunctions start-execution --state-machine-arn $SM --input "$1" --query executionArn --output text)
while [ "$(aws stepfunctions describe-execution --execution-arn $ARN --query status --output text)" = "RUNNING" ]; do sleep 3; done
aws stepfunctions describe-execution --execution-arn $ARN --query '[status,error,output]' --output text
echo "จำนวนครั้งที่ Lambda พัง: $(aws stepfunctions get-execution-history --execution-arn $ARN \
--query 'length(events[?type==`TaskFailed`])' --output text)"
}
run '{"orderId":"o-3001","amount":250,"mode":"ok"}'
run '{"orderId":"o-3002","amount":0,"mode":"ok"}'
run '{"orderId":"o-3003","amount":990,"mode":"broken"}'ผลที่ควรเห็น:
SUCCEEDED None {"orderId":"o-3001","amount":250,"mode":"ok","reserve":{"reservation":{"reservationId":"rsv-o-3001","items":1}}}
จำนวนครั้งที่ Lambda พัง: 0
FAILED InvalidOrder None
จำนวนครั้งที่ Lambda พัง: 0
FAILED ReserveFailed None
จำนวนครั้งที่ Lambda พัง: 4→ ชื่อ error TransientError ที่ Lambda โยน (จาก this.name) ไปถึง Step Functions ตรงตัวผ่าน integration lambda:invoke เป็นค่า error ของ TaskFailed จึง match กับ ErrorEquals ได้ · กรณีสุดท้าย: ลองครั้งแรก + retry 3 ครั้ง (รอ 1, 2, 4 วินาที) = พัง 4 ครั้ง แล้ว Catch พาไปขั้นชดเชยก่อนจบแบบ ReserveFailed · ข้อมูลผิด (amount 0) ไม่ถูก retry เพราะแยกทางที่ Choice ตั้งแต่ต้น
เปิดคอนโซล Step Functions → lab-order-flow → execution ล่าสุด → ดู Graph view จะเห็นเส้นทางสีแดงไป Compensate
เก็บกวาด
aws stepfunctions delete-state-machine --state-machine-arn $SM
aws lambda delete-function --function-name lab-flaky
aws logs delete-log-group --log-group-name /aws/lambda/lab-flaky
aws iam delete-role-policy --role-name lab-sfn-role --policy-name invoke-flaky
aws iam delete-role --role-name lab-sfn-role
aws iam detach-role-policy --role-name lab-flaky-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws iam delete-role --role-name lab-flaky-role
cd .. && rm -rf sfn-labกับดักที่เจอบ่อย
| อาการ | สาเหตุ / แก้ |
|---|---|
States.Runtime / JsonPath ... could not be found |
ใช้ $.field ที่ไม่มีใน input หรือลืม .$ ต่อท้ายชื่อ key ที่ต้องการให้อ่านค่าจาก path |
| output ทับ input เดิมหายหมด | ไม่ได้ตั้ง ResultPath (ค่าเริ่มต้นแทนที่ทั้ง state) |
| Retry ไม่ทำงาน | ชื่อ error ใน ErrorEquals ไม่ตรงกับ errorType ที่ Lambda โยน (ดูใน execution history) |
| retry แล้วตัดบัตรซ้ำ | งานใน Task ไม่ idempotent — ส่ง idempotency key (เช่น execution name) ไปปลายทาง |
AccessDeniedException ตอน invoke |
role ของ state machine ไม่มี lambda:InvokeFunction บน ARN นั้น (รวม :* ถ้าเรียก version/alias) |
| บิล Standard สูงจากลูปถี่ | งานถี่สูงสั้นๆ ย้ายไป Express หรือใช้ Map แบบ Distributed |
สรุปจำง่าย
ธุรกรรมหลายขั้นที่ต้องสำเร็จครบหรือชดเชย → Step Functions — แจ้งข่าวให้หลายระบบ → อีเวนต์ — Retry เฉพาะ error ชั่วคราว พร้อม backoff — Catch ไปขั้นชดเชย เก็บ error ไว้ใน ResultPath — Standard สำหรับธุรกิจ Express สำหรับงานถี่สั้น — ทุกขั้นที่ retry ได้ต้อง idempotent