Explain it simply
Think of a restaurant kitchen
The waiter takes an order, clips the ticket to the kitchen rail and goes straight back to the next customer. Cooks take tickets at their own pace. If a ticket arrives twice, they check its number and do not cook it again. If the card was charged but an ingredient has run out, the money is refunded.
This project is that kitchen. The API is the waiter, EventBridge and SQS are the ticket rail, the Lambda worker is the cook, DynamoDB is the order book, and Step Functions is the manager who watches the 'charge, reserve, refund if needed' process through to the end.
Problem → Why → Solution
Doing everything inside one request
First versions often have one 'POST /orders' handler that charges the card, decrements stock and sends the email. On the day the payment provider slows down, the request exceeds the API Gateway integration timeout and the customer sees an error, yet the card was already charged. They press 'Buy' again and are charged twice.
Moving the work behind a queue creates a new problem: an SQS standard queue delivers at least once, so occasionally a message arrives twice. The naive handler below receives one message twice and decrements the stock twice.
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 9Why it breaks
In a distributed system, 'exactly once' delivery cannot be guaranteed while networks and retries exist. What you can do is make the effect happen once (idempotency) and make a multi-step business process repairable when it stops halfway (compensation).
One component, one job
The core rule of this architecture is one job per component. The API validates, publishes an 'OrderPlaced' event to a custom event bus and returns 202 Accepted. Even when the payment provider is slow, the API stays fast.
EventBridge routes by the event's content using rules, so new consumers such as analytics or email join later by adding a rule, without touching the producer. SQS is the buffer: it absorbs spikes, redelivers messages that failed, and moves a message to the DLQ after maxReceiveCount attempts.
The Lambda worker writes the order to DynamoDB exactly once with a conditional write, then starts the Step Functions saga named after the order id. The saga is the business transaction: charge, reserve, confirm. If reserving fails, it refunds and marks the order CANCELLED. Where there is no database rollback, you undo with an opposite action: a 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
- The property that running an operation once or many times gives the same result. Here, the 'attribute_not_exists(PK)' condition lets the order record be created only once, and naming the saga execution after the order id means the saga also starts only once.
| Component | Job | Must not |
|---|---|---|
| API + Ingest | Validate, publish, 202 | Wait for payment |
| EventBridge | Route by content | Hold business logic |
| SQS + DLQ | Buffer, retry, park poison | Swallow failures silently |
| Worker | Write once, start saga | Charge cards itself |
| Saga | Steps + compensation | Retry errors blindly |
Why put SQS between EventBridge and Lambda instead of invoking Lambda directly? EventBridge is great at routing, but it is not a buffer that lets the consumer control its pace (batch size, concurrency). With SQS, the worker pulls at its own speed, individual messages can fail, and failures wait in a DLQ for inspection.
Know the price of this design too. The system is eventually consistent, so after the 202 the client must poll the order status or wait for a notification. For a simple CRUD app with a single consumer, a bus and a saga are complexity you do not need.
- API: validate, publish, 202
- Bus: route by content
- Queue: buffer, retry, DLQ
- Worker: conditional write once
- Saga: steps + compensation
Every stage must have an answer to: 'what happens if I receive this message again?'
The event contract: the 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 adds the envelope (id, source, detail-type, time) and your data sits in 'detail'. Rules match on source and detail-type. 'id' is unique per event and the worker stores it for debugging, but the idempotency key is the business key, orderId: a client retry can produce a new event id while the orderId stays the same.
The idempotent worker (Python, Lambda 3.12)
This handler receives an SQS batch and treats every message independently. The sample batch holds a normal order, a redelivery of that same order, a business-invalid order with total = 0, and a message that is not JSON at all. Watch how the three kinds of failure are handled differently.
"""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))Not runnable in the browser
This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.
Code breakdown
- Conditional put
ConditionExpression="attribute_not_exists(PK)"Writes only if the item does not exist yet. If it does, DynamoDB raises ConditionalCheckFailedException and we treat it as a duplicate, not an error. Because it is one conditional write rather than read-then-write, two concurrent workers cannot race.
- InvalidOrder
raise InvalidOrder("total must be positive")A failed business rule will never be fixed by retrying. So the order is recorded as REJECTED and not reported as a failure, instead of retrying five times for nothing and polluting the DLQ.
- ensure_saga
name=detail["orderId"]With the order id as execution name, a second start raises ExecutionAlreadyExists, which we ignore. ensure_saga runs even for duplicates on purpose: if the first delivery wrote the record and then crashed before starting the saga, the retry still starts it.
- batchItemFailures
failures.append({"itemIdentifier": msg_id})For an unexpected error (here JSONDecodeError) only that message id is returned. With reportBatchItemFailures enabled on the event source mapping, the three successful messages are deleted and only m-4 is retried; after five receives it lands in the 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
New or duplicate
Deleted from queue, saga runs once
Unexpected error
Retried, then DLQ + alarm
The full infrastructure (CDK)
The stack below creates every box in the diagram, and each number has a reason. The queue's 180-second visibility timeout is six times the worker's 30-second timeout: AWS recommends at least six times for an SQS event source, otherwise a message becomes visible again while the worker is still busy and is processed twice.
maxConcurrency: 20 caps the worker at twenty concurrent instances, protecting the payment provider and the account's concurrency. In the saga, ChargePayment retries only the known-transient 'PaymentProviderBusy' error, while RefundPayment retries up to five times, because a compensation must finish.
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();Status updates without a Lambda
MarkConfirmed and MarkCancelled use DynamoUpdateItem, a Step Functions direct service integration. No Lambda function means less code, no cold start and fewer moving parts.
Failure handling end to end
You can trust an event-driven system only when every failure has a defined place where it is handled. Use the table below as a design-review checklist: if the 'where you see it' column is empty, that failure will vanish silently.
| Failure | What happens | Where you see it |
|---|---|---|
| EventBridge cannot deliver to SQS | EventBridge retries per its retry policy (up to 24 hours by default) | Rule FailedInvocations metric; add a target DLQ |
| Worker throttled or timed out | The message becomes visible again and is retried | Lambda Throttles, queue age |
| Poison message | DLQ after 5 receives | DlqNotEmpty alarm |
| Duplicate delivery | The conditional put skips it | 'duplicate' log line |
| Charge fails | MarkCancelled → OrderFailed | Saga FAILED executions |
| Reserve fails | Refund → MarkCancelled → OrderFailed | Saga FAILED + refund result |
When the compensation itself fails
If all five refund retries fail, the saga ends FAILED with the card still charged. That is a case for a human. Put a CloudWatch alarm on failed saga executions and write in the runbook how to issue the refund by hand.
Operating it: test, watch, redrive
Send a test event
Skip the API and put-events directly on the bus. A wrong rule pattern shows up immediately at this step.
Watch the queue
If ApproximateNumberOfMessages keeps rising, the worker is failing or being throttled.
Fix the bug, then redrive
Move DLQ messages back to the source queue with start-message-move-task. Redriving before the fix just sends them back to the DLQ. Because the worker is idempotent, redrive is safe.
# 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 10In production
In production
Production teams treat the event schema as a contract. Adding fields is allowed; removing a field or changing its meaning requires a new version (OrderPlaced.v2). The EventBridge Schema Registry or JSON Schemas kept in the repo let consumer teams know in advance.
Many teams store idempotency records under the business key with the idempotency utility of Powertools for AWS Lambda rather than hand-rolling it, because it handles TTLs, in-progress state and payload hashing completely.
Dashboards show queue age (ApproximateAgeOfOldestMessage), DLQ depth, failed saga count and end-to-end latency from OrderPlaced to CONFIRMED. To trace a single order, the orderId goes into every log line and into X-Ray trace annotations.
Finally, teams rehearse failure on purpose. In a staging account they block the payment endpoint, push a poison message, or set the worker's reserved concurrency to zero, and confirm that every alarm fires and every runbook step works before a real customer depends on it.
Common mistakes
Common mistakes
Failing the whole batch
Without reportBatchItemFailures, raising an exception out of the handler sends all ten messages back when one fails. The nine that succeeded are processed again and, without idempotency, all nine have a double effect. Enable reportBatchItemFailures and return only the failed ids. Note that the setting must be on in both places: in the event source mapping and in the response your handler returns.
Retrying every error
Retrying 'States.ALL' on the charge step also retries card declines (business errors) and can get you fraud-blocked by the provider. Retry only named transient errors, and send an idempotency key (orderId) with every payment call.
A DLQ nobody watches
A DLQ only stores failures. Without an alarm, messages silently expire after the retention period (14 days here) and customer orders are lost. Alarm on DLQ depth greater than zero, and make sure the alarm reaches a person who knows the redrive procedure.
Best practices
Best practices
- Use the business key (orderId), not the event id, as the idempotency key
- Set visibility timeout to at least six times the consumer timeout
- Handle business errors, poison messages and transient errors differently
- Give compensation steps more retries and an alarm
💰 Cost & Cleanup
Everything here is serverless, so idle cost is close to zero. API Gateway (per request), EventBridge custom events (per million), SQS (per request), Lambda (requests plus duration), DynamoDB on-demand (per read/write) and Step Functions Standard (per state transition) all have free tiers that usually cover lab traffic. PITR adds a backup charge based on table size. Watch costs if you load test. Afterwards, delete the stack and the log groups.
Clean up when you are done
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
Make events replayable after a bug fix
Suppose a worker bug mis-processed three days of orders. Add an archive to the 'orders' bus so those events can be replayed once the bug is fixed.
- Archive only OrderPlaced events
- Keep them for 30 days
- Explain why the worker handles replayed duplicates safely
Expected: Synth shows an AWS::Events::Archive resource. On replay, existing orders are skipped as duplicates and only missing ones are written, thanks to the conditional put.
Show hint
EventBus has an archive() method. A replay is started from the console or with 'aws events start-replay'.
Show solution
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
What to remember
- The API publishes and returns immediately; slow work lives behind a queue
- Make at-least-once delivery idempotent with a conditional write on the business key
- Handle business errors, poison messages and transient errors differently
- Write multi-step transactions as a saga with compensation, and alarm when compensation fails
- Without alarms on DLQ depth, queue age and saga failures, failures disappear silently
Using Lambda with Amazon SQS — AWS Documentation
Amazon EventBridge User Guide — AWS Documentation
AWS Step Functions Developer Guide — AWS Documentation