ရိုးရိုးလေး ရှင်းပြမယ်
စားသောက်ဆိုင် မီးဖိုချောင်လို စဉ်းစားပါ
စားပွဲထိုးက order ကိုလက်ခံပြီး ticket ကို မီးဖိုချောင် rail ပေါ်မှာ ချိတ်လိုက်တယ်၊ ပြီးတော့ နောက် customer ဆီ ချက်ချင်း ပြန်သွားတယ်။ စားဖိုမှူးတွေက ticket တွေကို သူတို့အချိန်နဲ့ ယူချက်ကြတယ်။ Ticket တစ်ရွက် နှစ်ခါ ရောက်လာရင် ticket နံပါတ်ကို စစ်ပြီး ထပ်မချက်ဘူး။ ငွေချေပြီးမှ ပစ္စည်းကုန်နေရင် ငွေပြန်အမ်းတယ်။
ဒီ project က အဲဒီ မီးဖိုချောင်ပါပဲ။ API က စားပွဲထိုး၊ EventBridge နဲ့ SQS က ticket rail၊ Lambda worker က စားဖိုမှူး၊ DynamoDB က order စာအုပ်၊ Step Functions က 'ငွေချေ → ပစ္စည်းယူ → မရရင် ငွေပြန်အမ်း' ဆိုတဲ့ လုပ်ငန်းစဉ်ကို စောင့်ကြည့်ပေးတဲ့ မန်နေဂျာ ဖြစ်ပါတယ်။
Problem → Why → Solution
အရာအားလုံးကို request တစ်ခုထဲမှာ လုပ်ရင်
ပထမဆုံး version တွေမှာ 'POST /orders' handler တစ်ခုတည်းက card charge လုပ်တယ်၊ stock လျှော့တယ်၊ email ပို့တယ်။ Payment provider နှေးသွားတဲ့နေ့မှာ API Gateway ရဲ့ integration timeout ကို ကျော်ပြီး customer က error မြင်ရတယ် - ဒါပေမယ့် card ကို charge ပြီးသား ဖြစ်နေတယ်။ Customer က 'Buy' ကို ထပ်နှိပ်တော့ နှစ်ခါ charge ခံရတယ်။
Queue ထည့်ပြီး async လုပ်လိုက်ရင်လည်း ပြဿနာ အသစ်တစ်ခု ပေါ်လာပါတယ် - SQS standard queue က message တစ်ခုကို အနည်းဆုံး တစ်ကြိမ် (at-least-once) ပို့ပေးတာမို့ တစ်ခါတစ်ရံ နှစ်ကြိမ် ရောက်လာပါတယ်။ အောက်က naive handler က message တစ်ခုတည်းကို နှစ်ကြိမ် ရလိုက်တဲ့အခါ stock ကို နှစ်ခါ လျှော့လိုက်ပါတယ်။
import json
import boto3
table = boto3.resource("dynamodb").Table("inventory")
def naive_handler(event, context):
# "Decrement stock for every order message we receive."
for record in event["Records"]:
order = json.loads(record["body"])
table.update_item(
Key={"sku": order["sku"]},
UpdateExpression="ADD stock :minus",
ExpressionAttributeValues={":minus": -order["qty"]},
)
message = {"messageId": "m-1", "body": json.dumps({"sku": "mug", "qty": 1})}
naive_handler({"Records": [message]}, None)
naive_handler({"Records": [message]}, None) # SQS redelivers the same message
stock = table.get_item(Key={"sku": "mug"})["Item"]["stock"]
print(f"one order, stock went 10 -> {stock}") # 8, not 9ဘာကြောင့် ပျက်တာလဲ
Distributed system မှာ 'တစ်ကြိမ်တိတိ' (exactly once) ဆိုတာ network နဲ့ retry ရှိနေသရွေ့ အာမခံလို့ မရပါဘူး။ ကိုယ်လုပ်နိုင်တာက effect ကို တစ်ကြိမ်ပဲ ဖြစ်အောင် (idempotent) design လုပ်ဖို့နဲ့ step အများကြီးပါတဲ့ လုပ်ငန်းကို တစ်ဝက်တစ်ပျက်မှာ ရပ်သွားရင် ပြန်ပြင်နိုင်အောင် (compensation) design လုပ်ဖို့ပါ။
Component တစ်ခု = တာဝန်တစ်ခု
ဒီ architecture ရဲ့ အဓိက စည်းမျဉ်းက component တစ်ခုချင်းမှာ တာဝန်တစ်ခုပဲ ရှိရမယ်ဆိုတာပါ။ API က validate လုပ်ပြီး 'OrderPlaced' event ကို custom event bus ပေါ် publish လုပ်တယ်၊ ပြီးတာနဲ့ 202 Accepted ပြန်ပေးတယ်။ Payment provider နှေးနေလည်း API က မြန်နေဆဲပါ။
EventBridge က event ရဲ့ content ကိုကြည့်ပြီး rule တွေနဲ့ route လုပ်ပါတယ်။ ဒါကြောင့် နောက်ပိုင်း analytics, email စတဲ့ consumer အသစ်တွေကို producer ကို မထိဘဲ rule တစ်ခုထည့်ရုံနဲ့ ချိတ်လို့ရပါတယ်။ SQS က buffer ပါ - traffic spike ကို စုထားပေးတယ်၊ fail ဖြစ်တဲ့ message ကို ပြန်ပို့ပေးတယ်၊ maxReceiveCount ကျော်ရင် DLQ ထဲ ရွှေ့ပေးတယ်။
Lambda worker က order ကို DynamoDB ထဲ conditional write နဲ့ တစ်ကြိမ်ပဲ ရေးပြီး Step Functions saga ကို order id နဲ့ start လုပ်ပါတယ်။ Saga ကတော့ business transaction ပါ - charge, reserve, confirm။ Reserve fail ရင် refund လုပ်ပြီး order ကို CANCELLED လို့ မှတ်ပါတယ်။ Database transaction တစ်ခုလို rollback မရတဲ့နေရာမှာ ဆန့်ကျင်ဘက် action (compensation) နဲ့ ပြန်ညှိတာ ဖြစ်ပါတယ်။
ORDER FLOW
----------
client --POST /orders--> API Gateway --> Ingest Lambda
| PutEvents
v
EventBridge bus 'orders'
rule: source=shop.api, OrderPlaced
|
v
+---- maxReceiveCount=5 ---- SQS WorkerQueue (vis 180s)
v | batch of 10
SQS WorkerDlq --> alarm v
Worker Lambda: conditional put ORDER#id/META
| |
v v
DynamoDB StartExecution(name=orderId)
|
Step Functions saga: Charge --> Reserve --> MarkConfirmed
| | fails
| v
| Refund (retries)
v v
MarkCancelled --> OrderFailed- Idempotency
- Operation တစ်ခုကို တစ်ကြိမ် run တာနဲ့ အကြိမ်ကြိမ် run တာ ရလဒ် အတူတူ ဖြစ်တဲ့ ဂုဏ်သတ္တိပါ။ ဒီ project မှာ 'attribute_not_exists(PK)' condition နဲ့ order record ကို တစ်ခါပဲ ဖန်တီးလို့ရပြီး saga execution name ကို order id ထားလို့ saga လည်း တစ်ခါပဲ စပါတယ်။
| Component | တာဝန် | မလုပ်ရတာ |
|---|---|---|
| API + Ingest | Validate, publish, 202 | Payment ကို စောင့်နေခြင်း |
| EventBridge | Content အလိုက် route | Business logic ထည့်ခြင်း |
| SQS + DLQ | Buffer, retry, park poison | Failure ကို မျိုချခြင်း |
| Worker | တစ်ကြိမ်ပဲ ရေး၊ saga start | Card charge ကိုယ်တိုင်လုပ်ခြင်း |
| Saga | Steps + compensation | Retry မသေချာတဲ့ error တွေ |
EventBridge ကနေ Lambda ကို တိုက်ရိုက် invoke မလုပ်ဘဲ ကြားထဲမှာ SQS ဘာကြောင့် ထည့်ရလဲ? EventBridge က routing ကောင်းပေမယ့် consumer ဘက်က အရှိန် (batch size, concurrency) ကို ထိန်းပေးတဲ့ buffer မဟုတ်ပါဘူး။ SQS ရှိမှ worker က ကိုယ့်အရှိန်နဲ့ ယူတယ်၊ message တစ်ခုချင်း fail နိုင်တယ်၊ fail တာတွေကို DLQ ထဲမှာ စစ်ဆေးလို့ရတယ်။
ဒီ design ရဲ့ ပေးရတဲ့ တန်ဖိုးကိုလည်း သိထားပါ။ System က eventually consistent ဖြစ်လို့ client က 202 ရပြီးနောက် order status ကို poll လုပ် (သို့) notification စောင့်ရပါတယ်။ Consumer တစ်ခုတည်းရှိတဲ့ ရိုးရှင်းတဲ့ CRUD app အတွက်ဆိုရင် bus နဲ့ saga က မလိုအပ်တဲ့ ရှုပ်ထွေးမှုပဲ ဖြစ်ပါတယ်။
- API: validate, publish, 202
- Bus: route by content
- Queue: buffer, retry, DLQ
- Worker: conditional write once
- Saga: steps + compensation
အဆင့်တိုင်းက 'ဒီ message ကို နောက်တစ်ခါ ထပ်ရရင် ဘာဖြစ်မလဲ' ဆိုတဲ့ မေးခွန်းကို ဖြေထားရပါမယ်။
Event contract: OrderPlaced envelope
{
"version": "0",
"id": "evt-7f1c",
"detail-type": "OrderPlaced",
"source": "shop.api",
"account": "111122223333",
"time": "2026-11-08T09:30:00Z",
"region": "us-east-1",
"resources": [],
"detail": {
"orderId": "o-1001",
"customerId": "c-42",
"total": 59.9,
"items": [{ "sku": "mug", "qty": 1 }]
}
}EventBridge က envelope (id, source, detail-type, time) ကို ထည့်ပေးပြီး ကိုယ့် data က 'detail' ထဲမှာ ရှိပါတယ်။ Rule တွေက source နဲ့ detail-type ကို match လုပ်ပါတယ်။ 'id' က event တစ်ခုချင်းအတွက် unique ဖြစ်ပြီး worker က debug အတွက် မှတ်ထားပါတယ်၊ ဒါပေမယ့် idempotency key ကတော့ business key ဖြစ်တဲ့ orderId ပါ - client က retry လုပ်ရင် event id အသစ်ရနိုင်ပေမယ့် orderId က အတူတူပါပဲ။
Idempotent worker (Python, Lambda 3.12)
ဒီ handler က SQS batch တစ်ခုကို လက်ခံပြီး message တစ်ခုချင်းကို သီးခြား ကိုင်တွယ်ပါတယ်။ Sample batch ထဲမှာ ပုံမှန် order တစ်ခု၊ အဲဒီ order ပဲ ထပ်ရောက်လာတာ (redelivery)၊ total = 0 ဖြစ်နေတဲ့ business-invalid order တစ်ခုနဲ့ JSON မဟုတ်တဲ့ message တစ်ခု ပါပါတယ်။ Failure အမျိုးအစား သုံးမျိုးကို မတူတဲ့နည်းနဲ့ ကိုင်တွယ်တာကို သတိထားကြည့်ပါ။
"""Order worker: SQS batch -> idempotent DynamoDB write -> start the saga once."""
from __future__ import annotations
import json
import os
from decimal import Decimal
import boto3
from botocore.exceptions import ClientError
TABLE = boto3.resource("dynamodb").Table(os.environ.get("TABLE_NAME", "orders"))
SFN = boto3.client("stepfunctions")
SAGA_ARN = os.environ.get("STATE_MACHINE_ARN", "")
class InvalidOrder(Exception):
"""A business rule failed. Retrying will never fix it."""
def record_order(detail: dict, event_id: str) -> bool:
"""Write the order once. True = created now, False = already there."""
status = "PENDING"
if Decimal(str(detail.get("total", 0))) <= 0:
status = "REJECTED"
try:
TABLE.put_item(
Item={
"PK": f"ORDER#{detail['orderId']}",
"SK": "META",
"status": status,
"customerId": detail["customerId"],
"total": Decimal(str(detail.get("total", 0))),
"sourceEventId": event_id,
},
ConditionExpression="attribute_not_exists(PK)",
)
except ClientError as err:
if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
return False
raise
if status == "REJECTED":
raise InvalidOrder("total must be positive")
return True
def ensure_saga(detail: dict) -> None:
"""Execution name = order id, so a second start can never charge twice."""
try:
SFN.start_execution(
stateMachineArn=SAGA_ARN,
name=detail["orderId"],
input=json.dumps(detail),
)
except SFN.exceptions.ExecutionAlreadyExists:
pass # an earlier delivery already started it
def handler(event, context):
failures = []
for record in event["Records"]:
msg_id = record["messageId"]
try:
envelope = json.loads(record["body"]) # the EventBridge event
detail = envelope["detail"]
created = record_order(detail, envelope["id"])
ensure_saga(detail)
state = "new" if created else "duplicate"
print(f"{msg_id}: {detail['orderId']} {state} -> saga ensured")
except InvalidOrder as err:
print(f"{msg_id}: rejected ({err}), not retried")
except Exception as err: # unknown problem: let SQS retry, then DLQ
print(f"{msg_id}: unexpected {type(err).__name__} -> back to queue")
failures.append({"itemIdentifier": msg_id})
return {"batchItemFailures": failures}
def sqs_record(msg_id: str, body: str) -> dict:
return {"messageId": msg_id, "body": body}
if __name__ == "__main__":
placed = {
"id": "evt-7f1c",
"detail-type": "OrderPlaced",
"source": "shop.api",
"detail": {"orderId": "o-1001", "customerId": "c-42", "total": 59.9},
}
bad = dict(placed, id="evt-7f2d",
detail={"orderId": "o-1002", "customerId": "c-7", "total": 0})
batch = {"Records": [
sqs_record("m-1", json.dumps(placed)),
sqs_record("m-2", json.dumps(placed)), # same event delivered again
sqs_record("m-3", json.dumps(bad)),
sqs_record("m-4", "not-json"),
]}
result = handler(batch, None)
failed = [f["itemIdentifier"] for f in result["batchItemFailures"]]
print("batchItemFailures:", failed)
items = sorted(TABLE.scan()["Items"], key=lambda i: i["PK"])
print("orders:", ", ".join(f"{i['PK'][6:]}={i['status']}" for i in items))
runs = SFN.list_executions(stateMachineArn=SAGA_ARN)["executions"]
print("saga executions:", len(runs))Browser ထဲမှာ run လို့ မရပါ
ဒီ code ဟာ AWS account အစစ်ပေါ်မှာ run ရမယ့် code ဖြစ်လို့ browser playground ထဲမှာ run လို့ မရပါ။ ကိုယ့် terminal (သို့) AWS CloudShell ထဲမှာ စမ်းပါ။
Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Conditional put
ConditionExpression="attribute_not_exists(PK)"Item မရှိသေးမှသာ ရေးပါတယ်။ ရှိပြီးသားဆိုရင် DynamoDB က ConditionalCheckFailedException ပြန်ပေးပြီး ကျွန်တော်တို့က 'duplicate' လို့ ယူဆပါတယ် - error မဟုတ်ပါဘူး။ Read-then-write မလုပ်ဘဲ condition တစ်ခုတည်းနဲ့ စစ်လို့ worker နှစ်ခု တပြိုင်နက် run ရင်တောင် race condition မရှိပါဘူး။
- InvalidOrder
raise InvalidOrder("total must be positive")Business rule fail တာက retry လုပ်လို့ ဘယ်တော့မှ မပြင်နိုင်ပါဘူး။ ဒါကြောင့် REJECTED status နဲ့ မှတ်ပြီး failure list ထဲ မထည့်ပါဘူး - ငါးကြိမ် အလကား retry ပြီး DLQ ကို ညစ်ပတ်စေမယ့်အစား ချက်ချင်း ဆုံးဖြတ်လိုက်တာပါ။
- ensure_saga
name=detail["orderId"]Execution name ကို order id ထားလို့ saga ကို နှစ်ခါ start လုပ်ရင် ExecutionAlreadyExists ရပြီး ကျွန်တော်တို့ ignore လုပ်ပါတယ်။ Duplicate message အတွက်တောင် ensure_saga ကို ခေါ်ရတဲ့ အကြောင်းက - ပထမ delivery မှာ record ရေးပြီး saga မစခင် crash ဖြစ်ခဲ့ရင် retry က saga ကို စပေးနိုင်ဖို့ပါ။
- batchItemFailures
failures.append({"itemIdentifier": msg_id})မမျှော်လင့်တဲ့ error (ဒီမှာ JSONDecodeError) ကြုံရင် အဲဒီ message id ကိုပဲ ပြန်ပေးပါတယ်။ Event source mapping မှာ reportBatchItemFailures ဖွင့်ထားရင် အောင်မြင်တဲ့ message သုံးခုကို queue ကနေ ဖျက်ပြီး m-4 ကိုပဲ ပြန်ပို့ပါတယ်။ ငါးကြိမ်ကျော်ရင် DLQ ထဲ ရောက်ပါတယ်။
m-1: o-1001 new -> saga ensured
m-2: o-1001 duplicate -> saga ensured
m-3: rejected (total must be positive), not retried
m-4: unexpected JSONDecodeError -> back to queue
batchItemFailures: ['m-4']
orders: o-1001=PENDING, o-1002=REJECTED
saga executions: 1- Parse the EventBridge envelope
- Conditional put ORDER#id / META
- StartExecution(name = orderId)
- Report only unexpected failures
အသစ် (သို့) duplicate
Deleted from queue, saga runs once
မမျှော်လင့်တဲ့ error
Retried, then DLQ + alarm
Infrastructure အပြည့်အစုံ (CDK)
အောက်က stack က diagram ထဲက အစိတ်အပိုင်းအားလုံးကို ဖန်တီးပါတယ်။ Number တွေ တစ်ခုချင်းမှာ အကြောင်းပြချက် ရှိပါတယ်။ Queue ရဲ့ visibility timeout 180 စက္ကန့်က worker timeout 30 စက္ကန့်ရဲ့ ၆ ဆပါ - AWS က SQS event source အတွက် အနည်းဆုံး ၆ ဆ ထားဖို့ အကြံပြုပါတယ်၊ မဟုတ်ရင် worker က အလုပ်လုပ်နေတုန်း message က ပြန်မြင်ရပြီး နှစ်ခါ process ဖြစ်ပါတယ်။
maxConcurrency: 20 က worker ကို တပြိုင်နက် instance ၂၀ ထက် မပိုအောင် ကန့်သတ်ပြီး payment provider နဲ့ account concurrency ကို ကာကွယ်ပါတယ်။ Saga မှာ ChargePayment ကို 'PaymentProviderBusy' ဆိုတဲ့ transient error အတွက်ပဲ retry လုပ်ပြီး RefundPayment ကိုတော့ ငါးကြိမ်အထိ retry လုပ်ပါတယ် - compensation က မဖြစ်မနေ ပြီးဆုံးရမှာမို့ပါ။
import { App, Duration, RemovalPolicy, Stack, StackProps } from "aws-cdk-lib";
import * as apigw from "aws-cdk-lib/aws-apigateway";
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
import * as events from "aws-cdk-lib/aws-events";
import * as targets from "aws-cdk-lib/aws-events-targets";
import * as lambda from "aws-cdk-lib/aws-lambda";
import { SqsEventSource } from "aws-cdk-lib/aws-lambda-event-sources";
import * as sqs from "aws-cdk-lib/aws-sqs";
import * as sfn from "aws-cdk-lib/aws-stepfunctions";
import * as tasks from "aws-cdk-lib/aws-stepfunctions-tasks";
import { Construct } from "constructs";
class OrdersStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const py = (name: string, timeout = 10) =>
new lambda.Function(this, name, {
runtime: lambda.Runtime.PYTHON_3_12,
handler: "index.handler",
code: lambda.Code.fromAsset("lambda"),
timeout: Duration.seconds(timeout),
});
// Single table: PK=ORDER#<id>, SK=META (more item types join later)
const table = new dynamodb.TableV2(this, "Orders", {
partitionKey: { name: "PK", type: dynamodb.AttributeType.STRING },
sortKey: { name: "SK", type: dynamodb.AttributeType.STRING },
billing: dynamodb.Billing.onDemand(),
pointInTimeRecoverySpecification: { pointInTimeRecoveryEnabled: true },
removalPolicy: RemovalPolicy.DESTROY, // lab only: RETAIN in production
});
// 1) API -> custom bus. The API only validates and publishes.
const bus = new events.EventBus(this, "Bus", { eventBusName: "orders" });
const ingest = py("Ingest");
ingest.addEnvironment("BUS_NAME", bus.eventBusName);
bus.grantPutEventsTo(ingest);
new apigw.LambdaRestApi(this, "Api", { handler: ingest });
// 2) Saga: charge -> reserve stock -> confirm, refund if reserve fails.
const orderKey = {
PK: tasks.DynamoAttributeValue.fromString(
sfn.JsonPath.format("ORDER#{}", sfn.JsonPath.stringAt("$.orderId")),
),
SK: tasks.DynamoAttributeValue.fromString("META"),
};
const setStatus = (id: string, status: string) =>
new tasks.DynamoUpdateItem(this, id, {
table,
key: orderKey,
updateExpression: "SET #s = :s",
expressionAttributeNames: { "#s": "status" },
expressionAttributeValues: {
":s": tasks.DynamoAttributeValue.fromString(status),
},
resultPath: sfn.JsonPath.DISCARD,
});
const charge = new tasks.LambdaInvoke(this, "ChargePayment", {
lambdaFunction: py("ChargeFn"),
resultPath: "$.payment",
});
// Retry only an error we KNOW is transient; the charge uses orderId as
// the payment provider's idempotency key, so a retry cannot double-charge.
charge.addRetry({ errors: ["PaymentProviderBusy"], maxAttempts: 3, backoffRate: 2 });
const reserve = new tasks.LambdaInvoke(this, "ReserveStock", {
lambdaFunction: py("ReserveFn"),
resultPath: "$.stock",
});
const refund = new tasks.LambdaInvoke(this, "RefundPayment", {
lambdaFunction: py("RefundFn"),
resultPath: "$.refund",
});
refund.addRetry({ maxAttempts: 5, backoffRate: 2 }); // compensation must finish
const cancelled = setStatus("MarkCancelled", "CANCELLED")
.next(new sfn.Fail(this, "OrderFailed", { error: "FulfilmentFailed" }));
charge.addCatch(cancelled, { resultPath: "$.error" });
reserve.addCatch(refund.next(cancelled), { resultPath: "$.error" });
const saga = new sfn.StateMachine(this, "OrderSaga", {
definitionBody: sfn.DefinitionBody.fromChainable(
charge.next(reserve).next(setStatus("MarkConfirmed", "CONFIRMED")),
),
timeout: Duration.minutes(5),
});
// 3) Rule -> queue (+DLQ) -> idempotent worker that starts the saga.
const dlq = new sqs.Queue(this, "WorkerDlq", { retentionPeriod: Duration.days(14) });
const queue = new sqs.Queue(this, "WorkerQueue", {
visibilityTimeout: Duration.seconds(180), // 6 x worker timeout
deadLetterQueue: { queue: dlq, maxReceiveCount: 5 },
});
new events.Rule(this, "OrderPlaced", {
eventBus: bus,
eventPattern: { source: ["shop.api"], detailType: ["OrderPlaced"] },
targets: [new targets.SqsQueue(queue)],
});
const worker = py("Worker", 30);
worker.addEnvironment("TABLE_NAME", table.tableName);
worker.addEnvironment("STATE_MACHINE_ARN", saga.stateMachineArn);
table.grantReadWriteData(worker);
saga.grantStartExecution(worker);
worker.addEventSource(
new SqsEventSource(queue, {
batchSize: 10,
reportBatchItemFailures: true, // retry only the failed messages
maxConcurrency: 20, // protect the payment provider
}),
);
// 4) Someone must hear about poison messages.
new cloudwatch.Alarm(this, "DlqNotEmpty", {
metric: dlq.metricApproximateNumberOfMessagesVisible({
period: Duration.minutes(1),
}),
threshold: 0,
comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
evaluationPeriods: 1,
});
}
}
const app = new App();
new OrdersStack(app, "EventDrivenOrders");
app.synth();Saga ကို Lambda မပါဘဲ status update လုပ်ခြင်း
MarkConfirmed နဲ့ MarkCancelled က DynamoUpdateItem ဆိုတဲ့ Step Functions direct service integration ကို သုံးပါတယ်။ Lambda function မလိုတော့လို့ code နည်းတယ်၊ cold start မရှိဘူး၊ ပြင်စရာ နည်းပါတယ်။
Failure တစ်ခုချင်းကို အစအဆုံး ခြေရာခံခြင်း
Event-driven system ကို ယုံကြည်ရတဲ့ အကြောင်းက failure တိုင်းအတွက် ကိုင်တွယ်မယ့်နေရာ သတ်မှတ်ထားလို့ပါ။ အောက်က table ကို design review မှာ checklist အဖြစ် သုံးပါ - 'ဘယ်သူ့ဆီ ရောက်မလဲ' column ဗလာဖြစ်နေရင် အဲဒီ failure က တိတ်တိတ်လေး ပျောက်သွားမှာပါ။
| Failure | ဘာဖြစ်မလဲ | ဘယ်မှာ မြင်ရမလဲ |
|---|---|---|
| EventBridge က SQS ကို မပို့နိုင် | EventBridge က retry policy အတိုင်း (default ၂၄ နာရီအထိ) ပြန်ကြိုးစားပါတယ် | Rule ရဲ့ FailedInvocations metric၊ target DLQ ထည့်နိုင် |
| Worker throttle / timeout | Message ပြန်မြင်ရပြီး retry ဖြစ်ပါတယ် | Lambda Throttles, queue age |
| Poison message | ၅ ကြိမ် receive ပြီးရင် DLQ | DlqNotEmpty alarm |
| Duplicate delivery | Conditional put က skip လုပ်ပါတယ် | 'duplicate' log line |
| Charge fail | MarkCancelled → OrderFailed | Saga FAILED executions |
| Reserve fail | Refund → MarkCancelled → OrderFailed | Saga FAILED + refund result |
Compensation ကိုယ်တိုင် fail ရင်
Refund က retry ငါးကြိမ်လုံး fail ရင် saga က FAILED ဖြစ်ပြီး ငွေ charge ထားလျက်သား ကျန်ခဲ့ပါတယ်။ ဒါက လူကိုယ်တိုင် ဝင်ကိုင်ရမယ့် အခြေအနေပါ။ Saga FAILED executions အပေါ် CloudWatch alarm ထားပြီး runbook ထဲမှာ 'refund ကို ဘယ်လို လက်နဲ့ လုပ်မလဲ' ရေးထားပါ။
Operate လုပ်ခြင်း: စမ်းသပ်ခြင်း၊ စောင့်ကြည့်ခြင်း၊ redrive
Test event ပို့ပါ
API ကို ကျော်ပြီး bus ပေါ် တိုက်ရိုက် put-events လုပ်ပါ။ Rule pattern မှားနေရင် ဒီအဆင့်မှာ ချက်ချင်း သိရပါတယ်။
Queue ကို ကြည့်ပါ
ApproximateNumberOfMessages တက်နေပြီး မကျရင် worker အလုပ်မလုပ်နေတာ (သို့) throttle ခံနေရတာပါ။
Bug ပြင်ပြီးမှ redrive
DLQ ထဲက message တွေကို start-message-move-task နဲ့ source queue ဆီ ပြန်ရွှေ့ပါ။ Bug မပြင်ခင် redrive လုပ်ရင် DLQ ထဲ ပြန်ရောက်လာရုံပါပဲ။ Worker က idempotent ဖြစ်လို့ redrive က လုံခြုံပါတယ်။
# Publish a test event straight onto the bus (bypasses the API)
aws events put-events --entries file://test-order.json
# test-order.json:
# [{"EventBusName": "orders", "Source": "shop.api", "DetailType": "OrderPlaced",
# "Detail": "{\"orderId\":\"o-2001\",\"customerId\":\"c-1\",\"total\":12.5}"}]
# Is anything stuck? Visible = waiting, NotVisible = being processed now
aws sqs get-queue-attributes --queue-url "$QUEUE_URL" --attribute-names \
ApproximateNumberOfMessages ApproximateNumberOfMessagesNotVisible
# Failed sagas, newest first
aws stepfunctions list-executions --state-machine-arn "$SAGA_ARN" \
--status-filter FAILED --max-items 10
# After fixing the bug: move DLQ messages back to the source queue
aws sqs start-message-move-task --source-arn "$DLQ_ARN" \
--destination-arn "$QUEUE_ARN" --max-number-of-messages-per-second 10Production မှာ
Production မှာ
Production team တွေက event schema ကို contract တစ်ခုလို ဆက်ဆံပါတယ်။ Field အသစ် ထည့်တာကို ခွင့်ပြုပေမယ့် field ဖျက်တာ (သို့) အဓိပ္ပာယ် ပြောင်းတာကို version အသစ် (OrderPlaced.v2) နဲ့ပဲ လုပ်ပါတယ်။ EventBridge Schema Registry (သို့) repo ထဲက JSON Schema တွေနဲ့ consumer team တွေ ကြိုသိအောင် လုပ်ပါတယ်။
Idempotency record ကို business key နဲ့ သိမ်းပြီး Powertools for AWS Lambda ရဲ့ idempotency utility ကို သုံးတဲ့ team တွေလည်း များပါတယ် - ကိုယ်တိုင်ရေးတာထက် TTL, in-progress state, payload hash စတာတွေကို ပြီးပြည့်စုံစွာ ကိုင်တွယ်ပေးလို့ပါ။
Dashboard မှာ queue age (ApproximateAgeOfOldestMessage), DLQ depth, saga FAILED count နဲ့ end-to-end latency (OrderPlaced ကနေ CONFIRMED အထိ) ကို ပြထားပါတယ်။ Order တစ်ခုချင်းကို ခြေရာခံဖို့ orderId ကို log line တိုင်းနဲ့ X-Ray trace annotation မှာ ထည့်ပါတယ်။
နောက်ဆုံးအနေနဲ့ team တွေက failure ကို ရည်ရွယ်ချက်ရှိရှိ လေ့ကျင့်ပါတယ်။ Staging account မှာ payment endpoint ကို ပိတ်ကြည့်တာ၊ poison message ပို့ကြည့်တာ၊ worker ရဲ့ reserved concurrency ကို သုည ထားကြည့်တာတွေ လုပ်ပြီး customer အစစ် မမှီခိုခင် alarm တိုင်း မြည်လား၊ runbook step တိုင်း အလုပ်ဖြစ်လား စစ်ပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားများ
Batch တစ်ခုလုံးကို fail လုပ်ခြင်း
reportBatchItemFailures မဖွင့်ဘဲ exception ကို handler အပြင် ပစ်လိုက်ရင် message ၁၀ ခုထဲက တစ်ခု fail တာနဲ့ ၁၀ ခုလုံး ပြန်ရောက်လာပါတယ်။ အောင်မြင်ပြီးသား ၉ ခုကို ထပ် process လုပ်ရပြီး idempotency မရှိရင် ၉ ခုလုံး effect နှစ်ခါ ဖြစ်ပါတယ်။ Event source မှာ reportBatchItemFailures ဖွင့်ပြီး fail ဖြစ်တဲ့ id တွေကိုပဲ ပြန်ပေးပါ။ ဒီ setting က နေရာနှစ်ခုလုံးမှာ ရှိရပါမယ် - event source mapping မှာရော handler က ပြန်ပေးတဲ့ response မှာပါ။
Error တိုင်းကို retry လုပ်ခြင်း
Saga မှာ 'States.ALL' ကို charge step အတွက် retry လုပ်ရင် card decline ဖြစ်တာ (business error) ကိုလည်း ထပ်ကြိုးစားပြီး provider ဘက်က fraud block ခံရနိုင်ပါတယ်။ Retry ကို transient error အမည် သတ်မှတ်ထားတာတွေအတွက်ပဲ လုပ်ပြီး payment call တိုင်းမှာ idempotency key (orderId) ပါရပါမယ်။
DLQ ရှိပြီး ဘယ်သူမှ မကြည့်ခြင်း
DLQ က failure ကို သိမ်းထားပေးရုံပါ။ Alarm မရှိရင် message တွေ retention ကာလ (ဒီမှာ ရက် ၁၄) ကျော်ပြီး တိတ်တိတ်လေး ပျောက်သွားပြီး customer order တွေ ဆုံးရှုံးပါတယ်။ DLQ depth သုညထက်ကြီးရင် alarm ထားပြီး အဲဒီ alarm က redrive လုပ်ပုံ သိတဲ့ လူတစ်ယောက်ဆီ ရောက်ရပါမယ်။
Best Practices
Best practices
- Idempotency key ကို event id မဟုတ်ဘဲ business key (orderId) နဲ့ ထားပါ
- Visibility timeout ကို consumer timeout ရဲ့ အနည်းဆုံး ၆ ဆ ထားပါ
- Business error, poison message, transient error ကို ခွဲပြီး ကိုင်တွယ်ပါ
- Compensation step တွေကို ပိုများတဲ့ retry နဲ့ alarm ပေးပါ
💰 Cost & Cleanup
ဒီ project က serverless ဖြစ်လို့ idle ဖြစ်နေရင် ကုန်ကျစရိတ် နီးပါး မရှိပါဘူး။ API Gateway (request အလိုက်)၊ EventBridge custom event (million အလိုက်)၊ SQS (request အလိုက်)၊ Lambda (request + duration)၊ DynamoDB on-demand (read/write အလိုက်) နဲ့ Step Functions Standard (state transition အလိုက်) တွေမှာ free tier ပါလို့ lab အဆင့် traffic က အများအားဖြင့် free tier ထဲမှာ ကျပါတယ်။ PITR ဖွင့်ထားရင် table size အလိုက် backup ကြေး ရှိပါတယ်။ Load test လုပ်ရင်တော့ ကုန်ကျစရိတ်ကို စောင့်ကြည့်ပါ။ ပြီးရင် stack နဲ့ log group တွေကို ဖျက်ပါ။
စမ်းပြီးရင် ဖျက်ဖို့ command
cdk destroy EventDrivenOrders
# Lambda log groups are created at runtime, outside the stack: list, then delete
aws logs describe-log-groups --log-group-name-prefix /aws/lambda/EventDrivenOrders \
--query 'logGroups[].logGroupName' --output text
aws logs delete-log-group --log-group-name "$LOG_GROUP"Mini challenge
Bug ပြင်ပြီးရင် event တွေကို replay လုပ်နိုင်အောင်
Worker မှာ bug တစ်ခုကြောင့် ၃ ရက်စာ order တွေ မှားပြီး process ဖြစ်ခဲ့တယ်ဆိုပါစို့။ Bug ပြင်ပြီးနောက် အဲဒီ event တွေကို ပြန်ပို့နိုင်အောင် 'orders' bus မှာ archive တစ်ခု ထည့်ပါ။
- OrderPlaced event တွေကိုပဲ archive လုပ်ရမယ်
- ရက် ၃၀ သိမ်းထားရမယ်
- Replay လုပ်ရင် worker က duplicate ကို ဘာကြောင့် လုံခြုံစွာ ကိုင်တွယ်နိုင်လဲ ရှင်းပြနိုင်ရမယ်
ရလဒ်: Synth လုပ်ရင် AWS::Events::Archive resource တစ်ခုပေါ်လာပါမယ်။ Replay လုပ်ရင် ရှိပြီးသား order တွေက 'duplicate' အဖြစ် skip ဖြစ်ပြီး မရှိသေးတာတွေပဲ ရေးပါမယ် - conditional put ကြောင့်ပါ။
အရိပ်အမြွက် ကြည့်ရန်
EventBus မှာ archive() method ရှိပါတယ်။ Replay ကို console (သို့) 'aws events start-replay' နဲ့ start လုပ်ပါတယ်။
အဖြေ ကြည့်ရန်
import { App, Duration, Stack } from "aws-cdk-lib";
import * as events from "aws-cdk-lib/aws-events";
const app = new App();
const stack = new Stack(app, "OrdersArchive");
const bus = new events.EventBus(stack, "Bus", { eventBusName: "orders-lab" });
// Keep 30 days of order events so a fixed consumer can be replayed.
bus.archive("OrderEvents", {
archiveName: "orders-30d",
description: "OrderPlaced events for replay after consumer bugs",
eventPattern: { source: ["shop.api"], detailType: ["OrderPlaced"] },
retention: Duration.days(30),
});
app.synth();Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- API က publish လုပ်ပြီး ချက်ချင်း ပြန်ပေးတယ်၊ နှေးတဲ့အလုပ်တွေကို queue နောက်မှာ ထားပါ
- At-least-once delivery ကို business key နဲ့ conditional write ဖြင့် idempotent လုပ်ပါ
- Business error, poison message, transient error တို့ကို မတူတဲ့နည်းနဲ့ ကိုင်တွယ်ပါ
- Multi-step transaction ကို compensation ပါတဲ့ saga နဲ့ ရေးပြီး compensation fail ရင် alarm ထားပါ
- DLQ, queue age နဲ့ saga failure တွေမှာ alarm မရှိရင် failure တွေ တိတ်တိတ်လေး ပျောက်ပါတယ်
Using Lambda with Amazon SQS — AWS Documentation
Amazon EventBridge User Guide — AWS Documentation
AWS Step Functions Developer Guide — AWS Documentation