
One Order, One Stock Reservation: Retry-Safe Checkout on AWS
Build a retry-safe inventory reservation workflow with SQS, Lambda, and DynamoDB transactions. A practical single-SKU walkthrough with original Python code, three flowcharts, four illustrations, deployment steps, and honest test boundaries. Includes sandbox cleanup.
A customer clicks “Place order.” The connection stalls. They retry. Your worker receives the same order again.
If each delivery subtracts stock, one purchase can reserve inventory twice. The challenge is to make the business effect safe even when the transport repeats a message.
This tutorial builds a small AWS example for a fictional online shop selling blue mugs. It uses Amazon SQS, AWS Lambda, and an Amazon DynamoDB transaction. The code and seven visuals were created for this article with AI assistance and reviewed with local tests.
Validation scope: eight local unit tests passed against an in-memory test double. This walkthrough has not been deployed or load-tested in an AWS account. The deployment steps below are for a disposable sandbox and create billable resources.

1. Define the promise before choosing services
We start with five available units of
MUG-BLUE . Order O-1001 requests two. After the first reservation, three units remain. Replaying the identical order must leave the count at three.The promise is narrow: while the order ledger remains intact, the same order ID and content can create at most one committed stock reservation in this single-Region system.
This is not an exactly-once message-delivery claim. It does not cover payments, shipping, refunds, or reservation expiry. The example accepts one SKU per order and assumes an upstream trusted service owns globally unique order IDs. In a multi-tenant system, scope the key to the authenticated tenant as well.
SQS standard delivery can repeat messages; AWS explicitly recommends idempotent consumers. AWS: at-least-once delivery

2. The AWS architecture

- Trusted producer: validates the caller and sends an order with a stable
order_id.
- SQS standard queue: buffers work and supports retries.
- Lambda worker: validates and handles each record independently.
- DynamoDB table: stores both order reservations and stock balances.
- SQS dead-letter queue (DLQ): keeps unresolved work for investigation.
- CloudWatch: stores structured logs and evaluates a DLQ-depth alarm.
The worker is asynchronous. Successfully submitting a message means “queued,” not “inventory reserved.” A real checkout should expose a separate order-status endpoint or notification path; that frontend is outside this demo.
3. Put the ledger and the stock change in the same transaction
Our table has a string partition key called
pk :Key | Attributes | Purpose |
|---|---|---|
STOCK#MUG-BLUE | available=5 | Stock balance |
ORDER#O-1001 | sku=MUG-BLUE , quantity=2 , status=RESERVED | Durable reservation and replay guard |

The transaction conditionally creates the order only if its key does not exist. In the same transaction, it decrements stock only if the stock item exists and has enough units.
DynamoDB transactions make these changes all-or-nothing within the supported account and Region boundary.
BatchWriteItem is not a substitute for this atomic operation. Transaction request tokens provide a separate, time-limited retry feature; our durable protection comes from the order record's conditional creation. AWS: DynamoDB transactions Why not “check whether the order exists, then update stock”? Two workers could both read “missing” before either writes. The conditions must be enforced by the transaction, not a preceding application check.
Do not add a short TTL to the order ledger: once its row disappears, a delayed replay can become a new reservation. Retention and archival need an explicit replay policy.
4. Original worker implementation
Create
src/app.py with the following complete implementation. The Lambda Python runtime provides Boto3; for reproducible production packaging, pin and bundle a tested SDK version.

"""Original single-SKU reservation demo; no payment or shipping side effects."""import jsonimport loggingimport osimport re
LOG = logging.getLogger(__name__)LOG.setLevel(logging.INFO)CLIENT = NoneID = re.compile(r"[A-Za-z0-9_-]{1,64}\Z")
def validate(payload): if not isinstance(payload, dict): raise ValueError("Message must be an object") if set(payload) != {"order_id", "sku", "quantity"}: raise ValueError("Expected order_id, sku, quantity only") for key in ("order_id", "sku"): if not isinstance(payload[key], str) or not ID.fullmatch(payload[key]): raise ValueError("Invalid identifier") quantity = payload["quantity"] if type(quantity) is not int or not 1 <= quantity <= 100: raise ValueError("quantity must be an integer from 1 to 100") return payload
def reserve(client, table, payload): p = validate(payload) key = {"pk": {"S": "ORDER#" + p["order_id"]}} order = dict(key, sku={"S": p["sku"]}, quantity={"N": str(p["quantity"])}, status={"S": "RESERVED"}) try: client.transact_write_items(TransactItems=[ {"Put": { "TableName": table, "Item": order, "ConditionExpression": "attribute_not_exists(pk)"}}, {"Update": { "TableName": table, "Key": {"pk": {"S": "STOCK#" + p["sku"]}}, "UpdateExpression": "SET available = available - :q", "ConditionExpression": "attribute_exists(pk) AND available >= :q", "ExpressionAttributeValues": {":q": {"N": str(p["quantity"])}}}} ]) return "RESERVED" except client.exceptions.TransactionCanceledException: # A cancellation is not automatically a duplicate: inspect the ledger. existing = client.get_item( TableName=table, Key=key, ConsistentRead=True).get("Item") if existing: if (existing.get("sku") == order["sku"] and existing.get("quantity") == order["quantity"] and existing.get("status") == order["status"]): return "DUPLICATE" raise ValueError("Order ID reused with different content") # Insufficient stock, missing SKU, conflict, or another cancellation: # retry, then let the queue's redrive policy route unresolved work. raise
def process_batch(event, client, table): failures = [] for record in event["Records"]: try: outcome = reserve(client, table, json.loads(record["body"])) LOG.info(json.dumps({"message_id": record["messageId"], "outcome": outcome})) except Exception as error: # Do not log the body or exception text: either could contain data. LOG.warning(json.dumps({"message_id": record["messageId"], "outcome": "RETRY", "error_type": type(error).__name__})) failures.append({"itemIdentifier": record["messageId"]}) return {"batchItemFailures": failures}
def handler(event, context): global CLIENT if CLIENT is None: import boto3 CLIENT = boto3.client("dynamodb") return process_batch(event, CLIENT, os.environ["TABLE_NAME"])
Three details are deliberate:
- Cancellation is not proof of duplication. After a transaction cancellation, read the order ledger. A matching SKU, quantity, and
RESERVEDstatus establishes a safe replay for this model. A reused order ID with changed content is an error.
- A missing ledger row is not success. Insufficient stock, a missing SKU, or a transaction conflict remains failed work. The worker requests a retry rather than inventing a reservation.
- The duplicate check uses a strongly consistent table read. An eventually consistent read could temporarily miss a committed order. AWS: read consistency
Unexpected service or network exceptions also remain failures. If a request commits but the response is lost, another delivery can discover the committed order and safely acknowledge the replay. If a function times out before returning its response, more records may be delivered again; the transaction guard still matters.
5. Handle a mixed batch without discarding failed work
Imagine three messages: a new order, its identical replay, and an order requesting more stock than is available. The first two succeed; only the third message ID belongs in
batchItemFailures .

The event source mapping must enable
ReportBatchItemFailures ; returning that JSON without enabling the feature is insufficient. An unhandled function-level exception still fails the whole batch. This example uses a standard queue; FIFO requires additional ordering-aware handling. AWS: partial batch responses For this learning demo, malformed messages, conflicting order IDs, and insufficient stock retry and eventually enter the DLQ. That is a simple, visible exception workflow, not a complete customer-facing rejection system. A production design should persist a terminal rejection where appropriate, quarantine permanent input failures, and avoid repeatedly retrying hopeless work.
6. Deploy the supporting infrastructure
Create
template.yaml next to src/ . This original AWS SAM template includes the table, queue, DLQ, worker, log retention, and an alarm. The alarm has no notification destination; wire an approved notification or incident route before production use.AWSTemplateFormatVersion: '2010-09-09'Transform: AWS::Serverless-2016-10-31Description: Single-Region single-SKU retry-safe reservation learning demoResources: Ledger: Type: AWS::DynamoDB::Table Properties: BillingMode: PAY_PER_REQUEST AttributeDefinitions: - AttributeName: pk AttributeType: S KeySchema: - AttributeName: pk KeyType: HASH SSESpecification: SSEEnabled: true DeadLetters: Type: AWS::SQS::Queue Properties: MessageRetentionPeriod: 1209600 SqsManagedSseEnabled: true Orders: Type: AWS::SQS::Queue Properties: VisibilityTimeout: 180 MessageRetentionPeriod: 345600 SqsManagedSseEnabled: true RedrivePolicy: deadLetterTargetArn: !GetAtt DeadLetters.Arn maxReceiveCount: 5 Worker: Type: AWS::Serverless::Function Properties: Runtime: python3.12 Handler: app.handler CodeUri: src/ Timeout: 30 MemorySize: 256 Environment: Variables: TABLE_NAME: !Ref Ledger Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - dynamodb:PutItem - dynamodb:UpdateItem - dynamodb:GetItem Resource: !GetAtt Ledger.Arn Events: OrderBatch: Type: SQS Properties: Queue: !GetAtt Orders.Arn BatchSize: 10 FunctionResponseTypes: - ReportBatchItemFailures ScalingConfig: MaximumConcurrency: 2 WorkerLogs: Type: AWS::Logs::LogGroup Properties: LogGroupName: !Sub /aws/lambda/${Worker} RetentionInDays: 7 DeadLetterAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: Unresolved reservations require investigation Namespace: AWS/SQS MetricName: ApproximateNumberOfMessagesVisible Dimensions: - Name: QueueName Value: !GetAtt DeadLetters.QueueName Statistic: Maximum Period: 60 EvaluationPeriods: 1 Threshold: 0 ComparisonOperator: GreaterThanThreshold TreatMissingData: notBreachingOutputs: TableName: Value: !Ref Ledger QueueUrl: Value: !Ref Orders DeadLetterQueueUrl: Value: !Ref DeadLetters
The example uses a 30-second function timeout and 180-second queue visibility timeout. AWS recommends visibility of at least six times the function timeout, adding the batch window when configured, and a redrive
maxReceiveCount of at least five as a starting point. These are configuration choices to test under your workload, not latency guarantees. AWS: SQS event source configuration SAM's SQS event supports
FunctionResponseTypes ; its generated event source mapping connects the queue to the worker. AWS SAM: SQS event Use an AWS sandbox, an authenticated AWS CLI, AWS SAM CLI, and a supported Python 3.12 build environment. Review the generated IAM role before deployment. The worker's explicit DynamoDB policy is scoped to this table; SAM also supplies the execution/event-source permissions needed for logging and consuming the queue. No public API or public queue policy is created.
Run from the folder containing
template.yaml :sam buildsam deploy --guidedChoose a stack name such as
retry-safe-checkout-demo and one Region. Keep subsequent commands in that same Region. Deployment can incur charges; no resources were created in your AWS account while preparing this article.7. Run the real-world scenario in your sandbox
The commands below use Bash syntax and AWS CLI v2. Retrieve
TableName and QueueUrl from the stack outputs, then set them locally:export AWS_REGION=ap-south-1export TABLE_NAME='YOUR_STACK_TABLE_NAME'export QUEUE_URL='YOUR_STACK_QUEUE_URL'Seed the disposable SKU once. The condition prevents accidentally overwriting an existing balance; do not remove it to reset a live inventory item.
aws dynamodb put-item --table-name "$TABLE_NAME" --item '{"pk":{"S":"STOCK#MUG-BLUE"},"available":{"N":"5"}}' --condition-expression 'attribute_not_exists(pk)'Send the same business order twice. Two send operations can have different SQS message IDs; the application key is still
order_id .for attempt in 1 2; do aws sqs send-message --queue-url "$QUEUE_URL" --message-body '{"order_id":"O-1001","sku":"MUG-BLUE","quantity":2}'doneAllow the asynchronous worker to process the messages. Then inspect the two records using consistent reads:
aws dynamodb get-item --consistent-read --table-name "$TABLE_NAME" --key '{"pk":{"S":"STOCK#MUG-BLUE"}}'
aws dynamodb get-item --consistent-read --table-name "$TABLE_NAME" --key '{"pk":{"S":"ORDER#O-1001"}}'Expected, not cloud-measured here: stock is
3 , with one RESERVED order for quantity 2 . Logs should eventually show a reservation and an identical replay outcome, although transaction conflicts may cause intermediate retries.Next send
O-1002 with quantity 6 . It cannot reserve from the remaining three units. Expect no committed order row for O-1002 ; the unresolved message can reach the DLQ after repeated receives. Also replay O-1001 with quantity 1 : it must not alter stock or silently replace the original order.8. Test behavior, not just syntax

The accompanying source package includes eight standard-library unit tests. They passed locally against a small atomic in-memory fake, covering first reservation, duplicate delivery, changed content, insufficient stock, missing SKU, boolean quantity, mixed batches, and malformed JSON.
python -m unittest discover -s tests -vA short example of the replay assertion is:
def test_duplicate_does_not_decrement_twice(self): reserve(self.db, "demo", order()) self.assertEqual(reserve(self.db, "demo", order()), "DUPLICATE") self.assertEqual(self.stock(), 3)The fake checks application branching and output shape; it does not verify AWS service semantics, IAM, queue delivery, contention, or the template deployment. Before production, run integration tests in a disposable AWS environment, concurrent requests for the final stock unit, timeout-after-commit tests, and DLQ redrive tests. The test package is a companion artifact; the complete deployable worker and template are included inline above.
9. Production decisions this demo makes visible
- Authentication and authorization: keep the producer trusted. Never let a caller reserve another customer's order by guessing an ID. Scope keys by authenticated tenant where applicable.
- External side effects: do not add a payment charge after the transaction and assume the same guarantee. Use the payment provider's idempotency mechanism and a durable workflow/outbox design.
- Hot stock items: a single popular SKU is a contention point. Measure conflicts and capacity, cap concurrency deliberately, and load-test instead of assuming unlimited throughput.
- Retention: deleting the order ledger removes the replay guard. Cancellations and stock releases need separate, idempotent state transitions.
- Observability: watch DLQ depth and queue age, inspect
RETRY/DUPLICATEoutcomes, and monitor DynamoDB throttling and transaction failures. Do not log customer message bodies.
- Recovery: inspect the cause before redriving. Preserve the business order ID. Reconcile stock and the order ledger after recovery.
- Cost: queues, requests, transactional reads/writes, Lambda execution, logs, and alarms can all contribute. This is not a benchmark or a free-tier promise. Track actual usage in your selected Region.
10. Clean up the learning environment
After verifying the example, delete only the disposable stack you created. This removes its demo resources and data; export anything you intend to keep first. Check the SAM-managed deployment bucket separately because build artifacts may remain outside the application stack.
sam delete --stack-name retry-safe-checkout-demoThe lesson is practical: retries are normal. Put the replay guard and the inventory mutation inside one atomic boundary, then make failures observable and recoverable. The useful question is not “Can this message arrive twice?” It is “What happens to the business state when it does?”
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article