Project: Build an Async Order API with SQS, Lambda and DynamoDB (Source Code)
Flipkart flash-sale style: accept the order in milliseconds, process a moment later. Intake puts work on SQS; a worker Lambda writes DynamoDB.
In this chapter
- Why a queue in front of workers
- SQS + worker + table
- Return 202 Accepted
- Cleanup
1. Everyday example
If hundreds hit Place order together, a slow write path times out the API. SQS absorbs the spike; workers drain it.
HTTP API → intake Lambda → SendMessage → SQS → worker Lambda → DynamoDB PutItem. Client gets 202.
Download: async-order-api.zip
Accepted is different from completed
An order API can acknowledge a queued request before a worker finishes the order. The application needs a way to show that distinction.
Read all steps
- Submit order O-42
The API validates the request and places work on the queue. A successful acknowledgement means the work was accepted at this stage; it does not prove that payment, stock reservation or another later operation succeeded.
- The worker receives the message
The worker processes the message using its order ID. Receiving does not by itself delete an SQS message. A Lambda event source mapping manages polling and deletion after successful batch handling.
- Save the actual result
The worker records the resulting status. If a message is delivered again, the same order ID must not create a second business operation. Conditional writes or a suitable idempotency design help make retries safe.
- Show the student the difference
Check the immediate API response, then inspect or query the order status. A queue message, a worker log and a completed database record prove different stages. A failed worker should produce a visible failure or retry path, not a false success claim.
2. Lab
A. Queue + table
Draw two separate paths before configuring AWS. The browser needs a quick answer, so the intake Lambda validates the order and submits a small message to SQS. A queue holds messages until a worker can process them. The worker Lambda runs later and writes a DynamoDB item identified by orderId. Suppose the reply contains orderId=lab-17. Record it now even though the table may not yet show that order.
Define a finished order as one with its durable row and expected state. A 202 Accepted from intake says that processing was accepted. The worker could still be waiting or retrying. Design the status check around the returned order ID so the user does not need to submit another order to discover whether the first one finished.
- SQS Standard queue
yourname-orders. Copy URL. - DynamoDB
yourname-orders, PKorderId, on-demand.
B. Worker
The SQS trigger creates an event source mapping, a configuration that tells Lambda to poll the queue for messages and invoke the worker with a batch. While a received message is being worked on, SQS normally hides that message for the visibility timeout. A successful batch lets Lambda delete its messages. A failed batch can become visible again when the timeout passes.
Test one order and watch the worker logs and table rather than relying on a fixed sleep. A row with the exact order ID proves the write happened. Replay the same synthetic event in the lab and compare that row. A repeat delivery must have the same business outcome. For work such as a real charge, a keyed table write alone would not make the external charge safe to repeat.
- Role: logs + SQS consume + PutItem.
- Function worker.py, env TABLE_NAME. Add SQS trigger batch size 5.
C. Intake API
- Function intake.py, env QUEUE_URL, IAM sqs:SendMessage.
- HTTP API POST /orders. CORS *.
curl -s -X POST "$API_BASE/orders" -H 'content-type: application/json' \
-d '{"sku":"TEE-RED","qty":2}'
# Record orderId from 202 Accepted. Check the table using that ID after the worker processes it.
Cleanup
- Remove SQS trigger, both Lambdas, API, purge+delete queue, table, roles.
Common errors and fixes
These are synthetic practice situations. Diagnose the signal before changing a resource; no infrastructure changes are needed to read this guide.
Intake fails before a message reaches the queue.
QUEUE_URL must contain the SQS queue URL used by SendMessage, not its ARN. The intake role also needs permission to send to the intended queue. Compare the configured Region and queue identity with the error before touching the worker. A worker cannot repair an intake request that never successfully queued any work.
The worker reports success but the order is missing.
Do not catch a database error and then return success as if the batch completed. Lambda deletes SQS messages after successful batch processing. Inspect the worker error and write result; failed work must remain eligible for retry. For partial failures, both the event-source response setting and the handler response logic must agree.
Retrying creates a second business action.
SQS event-source processing is at least once. A worker can finish a database write and fail before the batch is acknowledged. Give the business order a stable identity and make repeat processing safe; generating a fresh order identity on every retry defeats that design. A duplicate delivery must not become a second charge or stock deduction.
Practical FAQ: decisions during real work
What should a client believe after an accepted response?
It means intake accepted the asynchronous request, not that inventory, payment or the worker has finished. A useful application exposes a status using the same order identity and distinguishes queued, completed and failed work. A quick response and a completed business transaction are different observations.
Why can one failed order make good orders reappear?
The default failure unit is the whole SQS batch. If four records finish and the fifth fails, those successful records may be delivered again. Partial batch responses can identify failed message IDs, but only when enabled and correctly implemented. They reduce unnecessary retries; they do not remove the need for idempotent business writes.
Does an empty queue prove that every order succeeded?
No. A message may be in flight, moved to a dead-letter queue, or already acknowledged after flawed application logic. Check worker errors, the DLQ and durable order status together. Queue depth measures pending delivery work; it is not a complete ledger of business outcomes.
3. Interview
Q. Why 202 not 201?
Accepted for async processing, not created finished.
Q. Standard vs FIFO?
FIFO for strict order + dedupe; Standard fine here.
Q. Worker failure?
Visibility timeout retry; DLQ after maxReceiveCount.
Q. Native API GW to SQS?
Yes — fewer parts; lab uses intake for clear code.
Q. Cleanup?
Queue, Lambdas, API, table.
Try at home
- Attach a DLQ after 3 receives.
- GET /orders/{id}.
In short
- Async = intake → SQS → worker → DynamoDB.
- 202 keeps API fast.
- Triggers + IAM matter.
- Clean queues too.
Test the acknowledgement and the worker
Use intake.lambda_handler and worker.lambda_handler. Keep the order ID returned by intake and use that ID to find the durable DynamoDB item, rather than assuming it appears within two seconds. Replay the same synthetic SQS event in the worker test and inspect how the lab overwrites the keyed row.
Interview check Does a successful 202 mean the worker completed?
It means intake accepted the request. The worker sees at-least-once delivery, and the supplied lab raises on an unhandled failure, which can replay the whole batch. A real worker must make side effects safe on retries even if partial batch responses are enabled.
Practise this chapter
Interview questions and answers
Why would you give the order API a status lookup in addition to its 202 response?
The 202 arrives as soon as intake accepts the work. A status lookup using the returned order ID lets the client see queued, completed or failed processing later without resubmitting the order. I would validate it against the durable record and the worker logs.
Check your understanding
Choose an answer, then compare your reasoning with the explanation.
Practice Tasks
Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.
About this scenarioDubai Gold Souk is a jewellery business in Dubai. Fatima Al Mansoori looks after its IT and cloud work. They count money in AED and run their AWS resources in the me-central-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.
0 / 12
Easy List functions
See which functions exist in this Region.
List the Lambda functions in me-central-1.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Invoke a function
Invoke runs the function now and saves its answer in a file.
Invoke dubaigold-orders-fn and save the response to out.json.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Trust policy for a Lambda role
The trust policy says WHO may take the role.
Write a trust policy that lets lambda.amazonaws.com assume the role.
- Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
- In each statement write Effect, Action and Resource.
- Give only what the task needs (least privilege).
- Use double quotes and commas correctly. Click Check answer.
Medium Put an item
DynamoDB JSON shows the type of each value: S for string, N for number.
Put an item into dubaigold-orders with orderId "o-101" (string) and amount 2500 (number).
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Change timeout and memory
More memory also gives more CPU; timeout stops runaway runs.
Set dubaigold-orders-fn to timeout 30 seconds and memory 512 MB.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Let a function write logs
Without these actions, Lambda logs never appear in CloudWatch.
Allow logs:CreateLogGroup, logs:CreateLogStream, logs:PutLogEvents on arn:aws:logs:*:*:* only.
- Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
- In each statement write Effect, Action and Resource.
- Give only what the task needs (least privilege).
- Use double quotes and commas correctly. Click Check answer.
Hard Connect an SQS queue to Lambda
An event source mapping makes Lambda poll the queue and process messages in batches.
Create an event source mapping from queue arn:aws:sqs:me-central-1:112884599412:dubaigold-orders to dubaigold-orders-fn with batch size 10.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Create a Lambda function
Lambda needs the code zip, a runtime, a handler name and an execution role.
Create function dubaigold-orders-fn: runtime python3.12, handler app.handler, role arn:aws:iam::112884599412:role/lambda-basic, code in function.zip.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Set environment variables
Keep settings like table names out of the code.
Set the environment variable TABLE=dubaigold-orders on dubaigold-orders-fn.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Invoke with a JSON payload
In CLI v2, raw JSON needs --cli-binary-format raw-in-base64-out.
Invoke dubaigold-orders-fn with payload {"orderId":"o-101"} (raw JSON) and save the reply in out.json.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Lambda GB-seconds
Lambda bills memory × time.
1,000,000 invocations, 512 MB memory, 200 ms each. How many GB-seconds?
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Hard Let S3 call your function
A resource-based permission is needed before S3 can invoke the function.
Add permission statement s3invoke to dubaigold-orders-fn so s3.amazonaws.com can call lambda:InvokeFunction from bucket arn:aws:s3:::dubaigold-uploads.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Revision, comparison and interview cards
Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.







More cards: Ravi Sir's Cards.