Test Order Retries with AWS Emulator, SQS, and DynamoDB
Build a Python inventory worker, crash it after a write, and verify duplicate delivery, atomic reservations, and failed-order recovery with AWS Emulator and real AWS.
I killed a Python worker after it reserved two tins of tea, before it acknowledged the queue message. When the message returned, inventory fell again: ten, eight, six. One order had reserved twice. A DynamoDB transaction kept the retry at eight. Both results reproduced on real AWS.
Build the same worker and inspect what survives its crash. You need basic Python, Git, and Docker; the business rule is simple: one order ID must reserve stock at most once, even when processing repeats.
AWS Emulator, launched November 11, 2026 , gives us local AWS API endpoints for this experiment. Start offline, then run the same assertions against AWS. The comparison checks reservation state and message handling; it does not establish IAM correctness or production capacity.
Give the retry somewhere to land
The application has three moving parts: an SQS standard queue holds orders, a Python worker processes them, and DynamoDB stores inventory and completed reservations. A dead-letter queue holds messages that repeatedly fail.
An order looks like this:
{"order_id": "order-1", "sku": "tea", "quantity": 2}The order ID belongs to the business operation. It survives a producer retry that sends a new SQS message with a different message ID. This demo assumes one merchant; a shared service would include the merchant identity in the key.
Receiving an SQS message temporarily hides it. Deleting it acknowledges processing. If the worker dies between those steps, the message can return after its visibility timeout. Standard queues can also deliver duplicates independently of crashes, so AWS recommends idempotent consumers .
Run the experiment locally
git clone https://github.com/rajmayank/talks-and-workshops.gitcd talks-and-workshopsgit checkout 885f85f5577ae508431076bf83c935c62280d565cd workshops/aws-emulator-order-retries/demosdocker build -t aws-order-retries .The build downloads dependencies. The run has no external network, mounted AWS credentials, or exposed ports. Python and the emulator communicate over loopback HTTPS inside the container, using the emulator's certificate and generated credentials. The process runs as an unprivileged user, with telemetry disabled.
The example pins emulator 1.0.509 and checks the downloaded package's checksum. AWS updates the emulator frequently; a pinned version makes a failed experiment easier to investigate. Check fidelity changes before upgrading .
Each scenario starts with ten available units and creates its own resources. The first two kill a real child process after the database write but before
DeleteMessage . The emulator stays running, and the next worker waits for SQS to redeliver the original message. Restarting the emulator would erase its in-memory state and test a different failure.Start with the deliberately broken worker. Here,
PASS means the test reproduced the bug: one order deducted stock twice.docker run --rm --network none --memory 2g --memory-swap 2g \ aws-order-retries --case naive-crashPASS naive crash: stock=10 -> 8 -> 6; reserved1 scenario(s) passed. Demo resources deleted.These terminal excerpts omit startup metadata. I captured them using Python 3.12 and emulator 1.0.509 in an arm64 Docker container.
Put the stock and its receipt in one transaction
The naive worker checks available stock and decrements it. That prevents a negative balance, but the repeated order still looks valid when enough stock remains.
Adding a separate “already processed” write leaves another crash window. Write the marker first and a crash can prevent the reservation forever. Write it second and a crash can allow another deduction.
The fix commits both changes together:
ddb.transact_write_items(TransactItems=[ {"Put": { "TableName": orders_table, "Item": order.item(), "ConditionExpression": "attribute_not_exists(order_id)", }}, {"Update": { "TableName": inventory_table, "Key": {"sku": {"S": order.sku}}, "UpdateExpression": "SET available = available - :qty", "ConditionExpression": "available >= :qty", "ExpressionAttributeValues": {":qty": {"N": str(order.quantity)}}, }},])order.item() contains the order ID, SKU, quantity, and RESERVED state. The first condition admits only an unseen order. The second requires enough stock. DynamoDB commits both actions or neither , so the order record is evidence that its stock deduction committed too.Predict the result before retrying the crashed worker: the record already exists, so the conditional insert fails. The entire transaction is canceled, including the stock deduction. Inventory remains eight.
Run the same crash with the transaction enabled:
docker run --rm --network none --memory 2g --memory-swap 2g \ aws-order-retries --case atomic-crashPASS atomic crash: stock=10 -> 8 -> 8; duplicate1 scenario(s) passed. Demo resources deleted.Each successful reservation writes two items. At up to 1 KB each, that consumes four write request units: two per item for prepare and commit, versus two for equivalent nontransactional writes. A strongly consistent retry read of an item up to 4 KB adds one read request unit. AWS capacity rules . A popular SKU remains a contention point; local tests cannot tell you its production throughput.
A canceled transaction is not automatically a duplicate
Transaction cancellation can mean insufficient stock or concurrent contention. Treating every cancellation as success would quietly discard orders.
The worker checks the stored reservation before acknowledging a retry. Inside
reserve() in worker.py , this branch handles the canceled transaction:except ClientError as exc: if exc.response["Error"]["Code"] != "TransactionCanceledException": raise existing = ddb.get_item( TableName=orders_table, Key={"order_id": {"S": order.order_id}}, ConsistentRead=True, ).get("Item") if not existing: raise if any(existing.get(key) != value for key, value in order.item().items()): raise OrderConflict("Order ID already belongs to a different reservation") from exc return "duplicate"The consistent read must find the same order ID, SKU, quantity, and
RESERVED state. Otherwise the error propagates and the message stays unacknowledged.DynamoDB also returns per-item cancellation reasons . Setting
ReturnValuesOnConditionCheckFailure="ALL_OLD" on the order Put can return the existing item when its condition fails, avoiding the extra read; TransactionConflict still needs a retry path. I kept the consistent read for one reconciliation rule across cancellation causes: acknowledge only when the stored reservation matches. That simplicity costs another request on canceled attempts.The acknowledgment stays after that decision:
outcome = reserve(ddb, order, orders_table, inventory_table)# The experiment exits the worker here, after the commit.sqs.delete_message( QueueUrl=queue_url, ReceiptHandle=message["ReceiptHandle"],)Use the receipt handle from the current delivery . If acknowledgment fails, another attempt can recognize the completed reservation. A database timeout is different: the outcome is uncertain, so the worker leaves the message available for retry instead of assuming the write failed or succeeded.
Now test two other routes to duplication: resending the order as a new SQS message, and starting two workers together.
docker run --rm --network none --memory 2g --memory-swap 2g \ aws-order-retries --case duplicate-send --case concurrentPASS duplicate sends: different message IDs; stock=8PASS concurrent workers: one reservation; stock=82 scenario(s) passed. Demo resources deleted.Try a conflicting retry. In
demo.py , inside duplicate_send_case() , change only second_id = send(sqs, queue_url) to second_id = send(sqs, queue_url, quantity=3) . Before running, decide whether reusing the order ID with a new quantity should count as a duplicate.docker build -t aws-order-retries-exercise .docker run --rm --network none --memory 2g --memory-swap 2g \ aws-order-retries-exercise --case duplicate-sendThe run should fail with
OrderConflict: Order ID already belongs to a different reservation . Matching the ID alone is insufficient. Undo that one-line edit afterward.Keep the order record for the entire supported replay period. Deleting it reopens the gate for an old message. The sample deliberately sets no TTL. DynamoDB's optional request-token deduplication has a ten-minute window , which cannot substitute for a business record needed beyond that window.
Decide what happens to orders that cannot proceed
For this experiment, insufficient stock is retryable. After three receives without successful processing, SQS moves the message to the dead-letter queue. A warehouse operator could replenish and redrive it, or cancel it through a separate workflow. Reaching the DLQ is not itself a customer-facing cancellation.
Request eleven of the ten available units, then separately reuse a reserved order ID with a different quantity:
docker run --rm --network none --memory 2g --memory-swap 2g \ aws-order-retries --case out-of-stock --case payload-conflictPASS insufficient stock: unchanged stock; DLQPASS payload conflict: unchanged stock; DLQ2 scenario(s) passed. Demo resources deleted.The first case also checks that no reservation record was written. The second verifies that the original reservation still contains its original quantity. A rejected request must leave the right state behind, not merely raise an exception.
The three-second visibility timeout makes the experiment quick. A real worker needs a timeout that accommodates processing and retries. The source queue retains messages for one day and the DLQ for fourteen, following AWS's guidance to make DLQ retention longer . Assign someone to resolve those messages before retention expires.
This guarantee ends at the DynamoDB transaction. Sending an email or charging a card afterward introduces another failure boundary that needs its own recovery design.
Repeat the checks on AWS, then verify cleanup
On November 18, 2026, all six scenarios passed against real SQS and DynamoDB in
us-east-1 , using host Python 3.9 and Boto3 1.42.97. The worker code was unchanged. Both environments reproduced the double deduction and preserved stock with the transactional worker.To repeat it, use Python 3.9+ and a configured sandbox profile. This run creates billable resources. Use the lab policy below for setup, execution, and deletion. Replace
123456789012 with your account ID and adjust the Region in both policies if needed. Save this as lab-policy.json :{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "dynamodb:CreateTable", "dynamodb:DescribeTable", "dynamodb:DeleteTable", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:GetItem" ], "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/order-lab-*" }, { "Effect": "Allow", "Action": [ "sqs:CreateQueue", "sqs:DeleteQueue", "sqs:GetQueueAttributes", "sqs:GetQueueUrl", "sqs:SendMessage", "sqs:ReceiveMessage", "sqs:DeleteMessage" ], "Resource": "arn:aws:sqs:us-east-1:123456789012:order-lab-*" } ]}DynamoDB transactions use the underlying item-action permissions , so there is no
dynamodb:TransactWriteItems action here. A production worker should not inherit the lab's create/delete permissions. From the project directory:python3 -m venv .venv. .venv/bin/activatepip install -r requirements.txtset -o pipefailpython run.py --aws-profile YOUR_SANDBOX_PROFILE \ --region us-east-1 --account-id YOUR_ACCOUNT_ID | tee aws-run.logThe runner checks the account before creating anything. Each scenario creates two on-demand tables and two queues with a unique prefix, then deletes them in
finally . A hard kill can bypass that cleanup, so keep the log and check its exact names using a separate verifier identity. Save its policy as cleanup-verifier-policy.json :{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "dynamodb:DescribeTable", "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/order-lab-*" }, { "Effect": "Allow", "Action": "sqs:GetQueueUrl", "Resource": "arn:aws:sqs:us-east-1:123456789012:order-lab-*" } ]}Configure
YOUR_VERIFIER_PROFILE for that identity. This policy grants only metadata reads; other attached policies can still grant writes. The account check uses sts:GetCallerIdentity , which requires no permission grant .python verify_cleanup.py --aws-profile YOUR_VERIFIER_PROFILE \ --region us-east-1 --account-id YOUR_ACCOUNT_ID --log aws-run.logThe checker only reads resource metadata. It waits for
DescribeTable and GetQueueUrl to return not-found errors; an access-denied error fails the check.Cleanup verified in us-east-1: 12 tables absent; 12 queues absent.The companion includes the complete text transcripts. These results cover the six assertions above, not broad emulator equivalence.
Both policy documents returned zero IAM Access Analyzer findings. All 170 IAM simulation checks matched the expected allow/deny results, including other prefixes, Regions, accounts, and verifier write attempts. These checks evaluate the policies in isolation, not live authorization or the account's combined permissions.
Conclusion
Kill the worker after the write, then inspect what the retry changes. That single experiment distinguishes a successful request from a repeatable business operation.
AWS Emulator made the failure cheap to repeat; the AWS run confirmed the same application outcomes. Neither run measured production capacity or tested least-privilege denials. The emulator does not reproduce IAM policy enforcement or production load behavior . Keep the local feedback loop fast and the claim narrow: repeated processing must preserve one inventory reservation.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article