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

AWS Cloud

Project: Build an OTP Notifier with Lambda, SNS and DynamoDB (Source Code)

UPI and banking apps send a one-time password. You will build a lab OTP API: store a keyed HMAC in DynamoDB and send the code by SNS email to one confirmed lab address.

In this chapter

  • Request and verify OTP flows
  • Hash + expiry in DynamoDB
  • SNS email for one confirmed lab address
  • Cost warnings and cleanup

1. Everyday example

Login without password for a minute: send 6 digits, user types them back. You must expire them fast and never store the raw OTP in plain text.

POST /otp/request and POST /otp/verify. Lambda makes a 6-digit code, stores a keyed HMAC with an expiry, then publishes to the classroom topic. The verifier consumes the code with a single conditional write.

Cost and sandbox

SNS SMS is billed per message and often starts in an SMS sandbox. This archive uses email only. Confirm one email subscription that you control. Remove extra subscribers before testing because SNS publishes to everyone subscribed to the topic.

Download: otp-notifier.zip

2. Lab

A. Table + topic

An OTP is a one-time password, usually a short code delivered to a user who must type it back. This classroom service uses one confirmed inbox so you can observe both requests without handling someone else’s mail. The DynamoDB item records the destination, a verification value, an expiry and state for one code. The inbox receives the digits. Avoid putting the digits or the secret in screenshots as you check the row.

The verification value is an HMAC, a value computed from data and a secret key. The handler can compute it again from a submitted code and compare it with the stored value. Someone holding only a copy of the table cannot repeat that same computation without the key. The short code still needs a time limit and a limit on wrong guesses.

  1. DynamoDB yourname-otps, PK dest String.
  2. SNS topic + email subscription (confirm). Copy TOPIC_ARN.

B. Lambda + API

Follow one successful verification. Request a code and read it only in the configured lab inbox. Submit it once before expiry. The conditional table update verifies it is still valid and unused, then marks it used in the same write. If two requests arrive together with that same code, only the first one that satisfies the condition can consume it. The second receives the unsuccessful response even if it submitted the right digits.

Test the difference between expiry and cleanup by using one synthetic expired test case. The code must be rejected at verification even while its row remains. DynamoDB TTL means Time to Live. It removes expired items later. The application’s expiry check enforces the deadline when someone tries the code.

  1. Role: logs, dynamodb:PutItem and dynamodb:UpdateItem on the lab table, and sns:Publish on the lab topic.
  2. Use handler.lambda_handler. Set TABLE_NAME, TOPIC_ARN, LAB_DEST to the confirmed email address, and OTP_HMAC_SECRET to at least 32 bytes of randomly generated text. Keep this value out of code, logs and screenshots.
  3. Test both paths with Lambda console events. If you add the HTTP API, use payload format 2.0 and AWS_IAM authorization on both POST routes and invoke with an authorized SigV4 client.

Use this Lambda console event with your own configured lab address. For the verify event, set rawPath to /otp/verify and add the emailed six-digit code to the body as otp.

{
  "requestContext": {
    "http": {
      "method": "POST"
    }
  },
  "rawPath": "/otp/request",
  "body": "{\"dest\":\"you@example.com\"}"
}

Cleanup

  1. Delete API, Lambda, table, topic, role. Delete OTP rows if any remain.
  2. Delete the lab's CloudWatch log group after saving any required non-secret test evidence.

3. Interview

Q. Why hash the OTP?

Six-digit values are too small to protect with an unkeyed hash alone. A keyed HMAC makes checking guesses against only the leaked table harder. Keep its key separate from the table.

Q. Why expiry?

OTPs are short-lived secrets; 5 minutes is common.

Q. SMS vs email lab?

Email SNS avoids SMS cost/sandbox for learning the flow.

Q. Rate limiting?

This lab gates the routes with IAM, requires a single configured destination, waits 30 seconds between requests, and caps failed guesses at five per active code. Runtime expiry still applies before TTL deletes a row.

Q. Cleanup?

API, Lambda, table, topic.

Try at home

  1. Verify that five failed guesses block further verification attempts for the same code.
  2. Use DynamoDB TTL on expiresAt.

In short

  1. OTP API = request + verify + hash + SNS.
  2. Prefer email in class.
  3. Never log raw OTP.
  4. Clean up.

Prove the code works only once

Use one confirmed email subscriber and test both routes in Lambda console events or behind AWS_IAM. Request a six-digit code for LAB_DEST, verify it once, then submit it again. Expect 200 and 400. Repeat with an expired code and a different destination. The archive enforces expiry in the conditional write, limits failed attempts and retains the consumed row for the 30-second request cooldown.

Interview check What prevents two simultaneous successful verify requests?

One conditional UpdateItem checks the digest, expiry, attempts and used state before removing the digest and setting used=true. Only one writer wins. TTL later removes the row. A keyed HMAC helps keep a table-only disclosure from exposing six-digit verifier values.

Reference documentation

Practise this chapter

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. What is stored for the verification step in the classroom OTP table?

Answer and explanation

A. A keyed HMAC and verification state

The keyed value can be recomputed when checking a code. The table does not need the plaintext code.

2. Two requests submit the correct OTP at the same time. What prevents both from consuming it?

Answer and explanation

A. A conditional table update checks validity and marks it used together

The condition is evaluated against the stored item as the write runs. After the first success, the unused condition fails.

3. The OTP row still exists after its expiry. Should verification accept the code?

Answer and explanation

A. No, the application’s expiry check still applies

TTL performs eventual cleanup, while the handler decides immediately whether the code is valid.

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

Stockholm Games is a gaming business in Stockholm. Erik Lindqvist looks after its IT and cloud work. They count money in SEK and run their AWS resources in the eu-north-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 eu-north-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 sthlmgames-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 sthlmgames-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 sthlmgames-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 Create a Lambda function

Lambda needs the code zip, a runtime, a handler name and an execution role.

Create function sthlmgames-orders-fn: runtime python3.12, handler app.handler, role arn:aws:iam::124495484726: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=sthlmgames-orders on sthlmgames-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 sthlmgames-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 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:eu-north-1:124495484726:sthlmgames-orders to sthlmgames-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 Let S3 call your function

A resource-based permission is needed before S3 can invoke the function.

Add permission statement s3invoke to sthlmgames-orders-fn so s3.amazonaws.com can call lambda:InvokeFunction from bucket arn:aws:s3:::sthlmgames-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.

OTP notifier with SNS. The Lambda generates a six-digit code and sends it to one confirmed SNS email subscriber. DynamoDB stores a keyed HMAC, expiry and attempt count. The raw code is never stored in the table. One conditional update validates and consumes the code. Test one successful use and then the same code again. Use Lambda console tests or IAM-authorized API routes. Set LAB_DEST, TOPIC_ARN and OTP_HMAC_SECRET.
Revision card: OTP notifier with SNS · Download PNG · Open card page
Hash and expire OTPs. A six-digit code has only one million possibilities. A plain hash is weak protection for a leaked table. Keep the HMAC key outside the table. Store the HMAC and an expiresAt Unix timestamp in seconds. Check expiry in the verifier and consume the code with a conditional update. DynamoDB TTL later clears the row.
Revision card: Hash and expire OTPs · Download PNG · Open card page
SNS email vs SMS cost. Keep one confirmed subscriber on the lab SNS email topic. Publishing sends to all confirmed subscribers. The current ZIP uses email only. Set LAB_DEST to the confirmed address and TOPIC_ARN to the lab topic. A separate SMS design needs region-specific pricing and sandbox or registration checks. No SMS sends are needed for the lab.
Revision card: SNS email vs SMS cost · Download PNG · Open card page
SNS email vs SMS for OTP practice. Use an SNS topic with one confirmed inbox. The classroom app accepts only the configured lab destination. Check per-message pricing, registration and sandbox restrictions before using SMS. The current ZIP sends email only. Use an authenticated request route, expiration and single-use verification. The delivery channel alone does not authenticate anyone.
Comparison: SNS email vs SMS for OTP practice · Download PNG · Open card page
Why protect a stored OTP?. A database copy plus a plain hash lets someone guess from a small six-digit space. Use a keyed HMAC and keep its key separate from the table. Do not log the OTP. Check expiry and failed attempts. One conditional update marks the OTP used and removes the digest.
Interview card: Why protect a stored OTP? · Download PNG · Open card page
Why prefer SNS email in class?. Email shows publish and subscribe using one confirmed test inbox. The lab ZIP has no SMS path. SMS pricing and sandbox or registration vary by destination and Region. Check them before a separate SMS rollout. Confirm the SNS subscription, set TOPIC_ARN and LAB_DEST, then test through Lambda or IAM-authorized routes.
Interview card: Why prefer SNS email in class? · Download PNG · Open card page

More cards: Ravi Sir's Cards.