Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

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.

Async pathClientPOST /ordersIntakeSendMessageSQSbufferWorkertriggerDynamoDBrow
API stays fast if worker is slow.

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.

Accepted is different from completedAPI response: 202: accepted for processing; SQS queue: Buffers the order message; Worker: Validates and processes the order; Order record: Shows processing outcome; Client status check: Reads the recorded outcomeAPI response202: accepted for processingSQS queueBuffers the order messageWorkerValidates and processes the orderOrder recordShows processing outcomeClient status checkReads the recorded outcome
Read all steps
  1. 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.

  2. 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.

  3. 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.

  4. 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.

  1. SQS Standard queue yourname-orders. Copy URL.
  2. DynamoDB yourname-orders, PK orderId, 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.

  1. Role: logs + SQS consume + PutItem.
  2. Function worker.py, env TABLE_NAME. Add SQS trigger batch size 5.

C. Intake API

  1. Function intake.py, env QUEUE_URL, IAM sqs:SendMessage.
  2. 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

  1. 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

  1. Attach a DLQ after 3 receives.
  2. GET /orders/{id}.

In short

  1. Async = intake → SQS → worker → DynamoDB.
  2. 202 keeps API fast.
  3. Triggers + IAM matter.
  4. 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.

Reference documentation

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.

0 of 3 answered correctly
1. The intake API returns 202 and an order ID. What can you tell the customer?

Answer and explanation

C. The request was accepted for later processing

The queue separates intake from the worker. A later check of the order ID establishes completed work.

2. A worker received a message but failed before acknowledging it. When may the message become available again?

Answer and explanation

C. After its visibility timeout

SQS normally hides an in-flight message temporarily. Failure can leave it eligible for another receive after the timeout.

3. What should stay stable when a duplicate delivery refers to the same business order?

Answer and explanation

B. The order ID

A stable business ID lets the worker detect or safely repeat the same operation. Receipt and invocation identifiers can change.

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 scenario

Dubai 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. 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).

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

Revision card: Why an async order API?. If checkout waits for inventory, fraud checks, and email, the shopper stares at a spinner and retries. Async intake: API accepts the order fast (HTTP 202), puts a message on SQS, and a worker Lambda writes DynamoDB later. Build SQS queue + DynamoDB PK orderId + intake Lambda (SendMessage) + worker Lambda (SQS trigger) + POST /orders. curl POST {"sku":"TEE-RED","qty":2} returns 202 in ~50 ms; ~2 s later DynamoDB shows status accepted.
Revision card: Why an async order API? · Download PNG · Open card page
Revision card: SQS as a buffer. A sudden flash sale can drown a single Lambda concurrency limit. Work must wait safely. Amazon SQS is a managed queue. Producers SendMessage; consumers receive later. Standard queue is fine for this lab. Create queue yourname-orders, grant intake sqs:SendMessage, grant worker consume + PutItem, add event source mapping batch size 5. If the worker is slow, messages pile in ApproximateNumberOfMessages; the API still returns 202.
Revision card: SQS as a buffer · Download PNG · Open card page
Revision card: HTTP 202 vs 201. Status codes tell clients what “success” means. Wrong codes confuse frontend retries. 201 Created = resource finished. 202 Accepted = request accepted for processing that is not done yet. Intake Lambda returns statusCode 202 and a body with orderId; worker creates the DynamoDB row asynchronously. Mobile app shows “Order received” immediately from 202, then polls GET /orders/{id} when you add it later.
Revision card: HTTP 202 vs 201 · Download PNG · Open card page
Comparison: Sync API to DynamoDB vs Async API via SQS. Sync API to DynamoDB: Caller waits until the row is written. Async API via SQS: Caller gets 202; worker writes later.
Comparison: Sync API to DynamoDB vs Async API via SQS · Download PNG · Open card page
Interview card: When do you return 202 Accepted?. When the server accepted work that will finish asynchronously. 201 would claim the order resource is fully created already. Intake SendMessage to SQS → 202 + orderId; worker writes DynamoDB afterward.
Interview card: When do you return 202 Accepted? · Download PNG · Open card page
Interview card: What happens when the worker keeps failing?. After visibility timeout the message reappears. After maxReceiveCount it can go to a dead-letter queue (DLQ). DLQ protects the main queue from poison messages and keeps a copy for debugging. Attach redrive policy maxReceiveCount=3 to an SQS DLQ on yourname-orders.
Interview card: What happens when the worker keeps failing? · Download PNG · Open card page
Interview card: Standard SQS or FIFO for this lab?. Standard is enough when strict ordering and deduplication are not required. FIFO adds ordering per message group and exactly-once processing features at lower throughput. Checkout intake lab uses Standard; use FIFO when order-of-events per customer must be strict.
Interview card: Standard SQS or FIFO for this lab? · Download PNG · Open card page

More cards: Ravi Sir's Cards.