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

AWS Cloud

DynamoDB Data Modeling and Single-Table Design for Beginners

Before you create another DynamoDB table, list how the app will read and write. Nairobi lead Amina Otieno and Pune founder Vikram Patil said: We modelled columns like MySQL, then every screen needed a Scan. Access-pattern-first and single-table thinking. Put/Get stays in CRUD and SDK. Intro: What Is Amazon DynamoDB?.

In this chapter

  • Explain the core idea with an everyday story
  • Apply Why / What / How on the topic
  • Read commands with sample output and meaning
  • Map the idea across industries
  • Complete the lab and cleanup

1. Everyday example: one notebook for the whole shop

A kirana notebook: tabs=PK, lines=SK. USER#, ORD#, ITEM# labels share one notebook (single-table). Tax notebook separate. Meera Kulkarni (Pune) keeps patients+appointments together; firmware inventory separate for IAM.

2. Vertical steps

Why -> What -> How -> Lab -> CleanupWhyWhatHowLabCleanup
Always cleanup lab resources

3. Purpose

DynamoDB rewards questions first. Attribute-first design causes Scans that get slow and costly. Hot paths must be GetItem or Query on one partition.

4. Overview

Single-table stores many entity types with overloaded PK/SK prefixes. Related items share a PK for one Query. Multi-table fits unrelated domains or different IAM/backup.

5. Steps

  1. Write 5-15 access patterns in English.
  2. Pick PK so hot patterns hit one partition.
  3. Pick SK for ranges/begins_with (ISO dates).
  4. Add EntityType for filters/Streams.
  5. Draw 8-10 sample items.
  6. Add GSI/LSI only for leftover patterns later.

6. CartLite key sketch

PK=USER#u100 SK=PROFILE; SK=ORD#2026-10-31T09:15#o2; PK=ORD#o2 SK=ITEM#sku9; PK=PROD#sku9 SK=META. Query USER for orders; Query ORD for lines.

7. Many-to-many edges

Kenji Watanabe (Osaka): STUD#/COURSE# and reverse edges. Thin edges; META for heavy fields; transactions in chapter 5.

8. Commands with output and meaning

aws dynamodb create-table --table-name lab-dda-shop \
  --attribute-definitions AttributeName=PK,AttributeType=S AttributeName=SK,AttributeType=S \
  --key-schema AttributeName=PK,KeyType=HASH AttributeName=SK,KeyType=RANGE \
  --billing-mode PAY_PER_REQUEST --region ap-south-1
# Output: TableStatus CREATING then ACTIVE
aws dynamodb put-item --table-name lab-dda-shop --item '{"PK":{"S":"USER#u100"},"SK":{"S":"PROFILE"},"EntityType":{"S":"User"},"name":{"S":"Ananya Rao"}}'
aws dynamodb query --table-name lab-dda-shop --key-condition-expression "PK = :pk" --expression-attribute-values '{":pk":{"S":"USER#u100"}}'
# Output: Count>=1. Meaning: item collection for that user PK.

create-table = on-demand HASH+RANGE lab. put-item adds User. query by PK returns the collection — the single-table read pattern.

9. Industry stories

  • Retail (Diego Alvarez + Ananya Rao): CartLite USER# orders; ORD# lines.
  • Logistics (Fatima Zahra, Casablanca): SHIP#+EVT# timeline.
  • EdTech (Sofia Alvarez, Bogota): CLASS#+POST# feed.
  • Bank (Lucas Meyer, Berlin): ledger vs marketing separate.
  • SaaS (Omar Haddad, Amman): TEN# tenant PK.
  • Media (Priya Nair, Kochi): watchlist with profile; invoices separate.

10. Lab

  1. Write 6 CartLite patterns; draw samples.
  2. Create lab-dda-shop; Put; Query USER# and ORD#.
  3. Delete table.

Cleanup (stop billing)

  1. Delete lab tables, indexes, and triggers you created.
  2. Confirm with describe-table that names are gone.

11. Access-pattern workshop (paper first)

  1. List every screen or API that reads or writes data.
  2. For each: write the exact key lookup or query shape in plain English.
  3. Mark 1:1, 1:many, many:many relationships.
  4. Circle anything that needs a sort range (time, status, score).
  5. Only then invent PK/SK and optional GSI keys.
  6. Estimate peak items per partition key per second.
  7. Write one sample item JSON for each entity type.
  8. Peer-review with someone who did not design it.

12. Copy-paste DynamoDB CLI starters

# Region habit for this series
export AWS_DEFAULT_REGION=ap-south-1

# Describe + sample
aws dynamodb describe-table --table-name ShopApp
aws dynamodb scan --table-name ShopApp --max-items 3

# Query by PK (replace names)
aws dynamodb query --table-name ShopApp   --key-condition-expression "PK = :pk"   --expression-attribute-values '{":pk":{"S":"USER#u123"}}'

# On-demand capacity mode check
aws dynamodb describe-table --table-name ShopApp   --query 'Table.BillingModeSummary'

# Streams status
aws dynamodb describe-table --table-name ShopApp   --query 'Table.StreamSpecification'

13. More industry stories

  • Retail (Aisha Khan, Dubai): single-table cart+orders; PK=USER#id keeps each shopper hot path local.
  • Gaming (Carlos Rivera, Mexico City): leaderboard uses sparse GSI on score; write shard on hot gameId.
  • IoT (Mei Lin, Shenzhen): sensor#day PK + timestamp SK; TTL 30 days keeps storage flat.
  • Healthcare (Rohan Deshmukh, Pune): appointment slots use conditional Put — no double book.
  • Fintech (Elena Petrova, Warsaw): Streams fan-out to audit table; never update audit in place.
  • Travel (Omar Haddad, Amman): global tables for read-local catalog; writes region-sticky for inventory.

14. Glossary (short)

TermMeaning
PK / Partition keyHash key that places the item in a partition
SK / Sort keyOrders items inside a partition; enables ranges
Item collectionAll items that share the same PK
GSIGlobal Secondary Index — alternate PK/SK, own partitions
LSILocal Secondary Index — same PK, different SK
RCU / WCURead/Write Capacity Units on provisioned mode
Conditional writeWrite succeeds only if a condition is true
Stream view typeKEYS_ONLY / NEW_IMAGE / OLD_IMAGE / NEW_AND_OLD_IMAGES

15. Practice: explain out loud

  1. 60s: why access patterns come before table design.
  2. 60s: hot partition and one fix (write sharding).
  3. 60s: GSI vs LSI in one breath.
  4. 60s: on-demand vs provisioned for a startup.
  5. 60s: optimistic locking with a version attribute.
  6. 60s: Streams + Lambda for an audit trail.
  7. Record once; cut filler; record again.

16. Safe lab hygiene

  • Use ap-south-1 labs with a budget alert (₹/USD).
  • Prefix lab tables with lab- and your initials.
  • Prefer on-demand for tiny labs unless you are learning auto scaling.
  • Delete tables and Lambda triggers after the lab.
  • Never point Streams consumers at production without a DLQ.
  • Tag every resource Owner + Expiry.

18. Single-table sketch pad

Write entities as rows in one mental table before you open the console. Example for a small shop: USER#, ORD#, ORD#|ITEM#, PROD# under carefully chosen PK/SK.

EntityPKSKExample attrs
UserUSER#u1PROFILEname, city
OrderUSER#u1ORD#2026-10-31#o9total, status
Order itemORD#o9ITEM#sku1qty, price
ProductPROD#sku1METAtitle, stock

19. Ten oral drill questions

  1. What is an access pattern?
  2. Why overload PK with entity prefixes?
  3. Name one hot-partition symptom.
  4. Sparse GSI means what?
  5. When is LSI impossible after create?
  6. On-demand bills for what?
  7. What does attribute_not_exists do?
  8. NEW_AND_OLD_IMAGES costs more — why still pick it?
  9. How do you stop a poison Streams message loop?
  10. Which existing chapter do you open for PutItem syntax?

20. Capacity and throttle drill

  1. Open CloudWatch for your table: ConsumedReadCapacityUnits, ConsumedWriteCapacityUnits, ThrottledRequests.
  2. Note whether BillingMode is PAY_PER_REQUEST or PROVISIONED.
  3. If provisioned, write current RCU/WCU and autoscaling min/max.
  4. Name your hottest expected PK in one sentence.
  5. Write one mitigation: shard, cache, or redesign.
  6. Set or verify a budget alert for DynamoDB.
  7. Check GSI list and whether each is still used.
  8. Confirm Streams enabled only where consumers exist.

21. Condition expression cheatsheet

# Create-once
attribute_not_exists(PK)

# Optimistic lock
version = :v

# Stock / seat
stock > :zero
#status = :free

# Combine
attribute_not_exists(PK) AND #type = :user

Meaning: conditions are the seatbelt for concurrent writers. Put them on every race-prone update. Full SDK samples stay in the SDK chapter — here we only list the expressions you will reuse.

22. Streams consumer checklist

  • View type matches need (KEYS_ONLY vs NEW_AND_OLD).
  • Lambda has DLQ and retry policy.
  • Handler idempotent on eventID or keys.
  • IteratorAge alarm before users feel lag.
  • No accidental write-loop back into the same table without markers.
  • Fan-out via SNS/EventBridge when >1 consumer team.
  • Disable stream when lab ends.
  • Ch1 Modeling -> Ch2 Hot keys -> Ch3 GSI/LSI -> Ch4 Capacity -> Ch5 Transactions -> Ch6 Streams.
  • Always link intro + CRUD + CLI + SDK instead of rewriting Put/Get.
  • Projects P1-P7 come in later batches and reuse these ideas.

24. Extra oral drills

  1. Explain single-table to a product manager in 45 seconds.
  2. Draw PK/SK for a chat thread on a whiteboard.
  3. Name three CloudWatch metrics for DynamoDB pain.
  4. Say when you would refuse a new GSI request.
  5. Describe one transaction for seat + payment record.
  6. Explain why Streams are at-least-once.
  7. Convert a Scan-based feature request into a Query design.
  8. List cleanup steps after a DynamoDB lab.

25. Teacher story: the notebook that became a database

Ravindra once watched a shop keep every customer, order and payment in one paper notebook. Finding last Tuesday's unpaid bills meant flipping pages. DynamoDB single-table thinking is that notebook done carefully: one place, clear labels (PK/SK), and an index tab (GSI) only when a second way to find rows is worth the cost. Do not photocopy the notebook into ten unrelated books unless the shop truly has ten separate businesses.

When Meera (clinic), Omar (travel), and Aisha (retail) design together, they still start on paper: screen list, key sketch, sample JSON, peer review. Console clicks come last. That ritual is why this deep series links the intro and CRUD chapters instead of rewriting PutItem on every page.

26. Sixteen mini tasks (self-check, leak-free)

  1. Write three access patterns for a cart app in one minute.
  2. Invent PK/SK for user profile and orders under that user.
  3. Name one hot-partition anti-pattern.
  4. Explain write sharding to a teammate in 40 seconds.
  5. Say GSI vs LSI without notes.
  6. Pick KEYS_ONLY or ALL for a sparse open-orders index — why?
  7. Choose on-demand or provisioned for a weekend flash sale.
  8. List five DynamoDB bill line-item types.
  9. Write a create-once condition in words.
  10. Describe optimistic locking with a version attribute.
  11. When do you wrap two writes in a transaction?
  12. Pick a stream view type for an audit log — justify.
  13. Name two Stream consumer safety rules.
  14. What CloudWatch metric shows stream lag?
  15. Which linked chapter has PutItem CLI syntax?
  16. Write your lab cleanup checklist (table, stream, lambda, alarms).

27. Marathi classroom lines (say out loud)

  • Access patterns आधी, keys नंतर — हे mantra आठवा.
  • Hot partition म्हणजे एक PK वर गर्दी — shard किंवा redesign.
  • GSI लवचिक; LSI create-time — चुकीचा index महाग.
  • On-demand म्हणजे वापरल्यावर पैसे; provisioned म्हणजे आरक्षित units.
  • Condition आणि transaction म्हणजे race साठी seatbelt.
  • Streams at-least-once आहे — handler idempotent ठेवा.

28. Hindi bridge lines

  • Pehle access patterns likho, baad mein PK/SK.
  • Hot partition ek key par zyada load.
  • GSI kabhi bhi; LSI table banate waqt.
  • On-demand spike ke liye; provisioned steady ke liye.
  • Transaction = sab milkar ya kuch nahi.
  • Streams duplicate de sakte hain — idempotent likho.

29. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
MySQL-first attributesPatterns first.
Email as PKOpaque userId.
Giant nested orders itemSplit + Query.
Forced single-tableSplit domains.
Bad SK time formatISO-8601.
No EntityTypeAdd it.
Scan for feedQuery model.
No sample drawingDraw first.
Copy Put instead of linkUse CRUD/SDK.

30. Troubleshooting checklist

  1. Empty Query: PK string + region.
  2. Wrong order: SK not sortable.
  3. Missing lines: under ORD# PK.
  4. Throttle one user: hot partition next ch.
  5. Need joins: DynamoDB vs RDS intro.

31. FAQ

Q. Should I always use a single table?

Often yes for related access patterns; not a religion. Separate tables are fine for unrelated domains or different capacity/security needs.

Q. Do I still need RDS?

Yes for heavy joins, multi-row SQL reports, and strong relational constraints. See the intro DynamoDB vs RDS chapter.

Q. Is Scan evil?

Scan is a tool for rare admin jobs and small tables. Design so hot paths use Query/GetItem.

Q. Where are Put/Get command details?

In the CRUD survey, CLI and SDK chapters — this deep set links them instead of copying.

Q. Single-table mandatory?

No — related patterns only.

Q. Entity count?

As patterns need.

Q. PutItem where?

CRUD/CLI/SDK.

Q. Change PK?

Migrate new table.

32. Interview Q&A

Q. (B) Access pattern?

Specific read/write in English before keys.

Q. (B) USER# prefix?

Many types; begins_with.

Q. (M) Multi-table when?

Unrelated/IAM/teams.

Q. (M) Adjacency list?

Edges both ways.

Q. (S/MNC) 50k users orders?

User+order partitions; load-test.

Q. (MNC) Avoid Scans?

Pattern review gate per screen.

33. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

Questions first; keys are answers.

Ravindra Bagale's Tip (MR)

आधी प्रश्न; keys उत्तरे.

Tip (HI)

पहले सवाल, फिर keys।

Try at home

  1. 8 patterns on paper.
  2. 3-entity collection draw.
  3. Re-read Query vs Scan in CRUD.

In short

  1. Patterns before attributes.
  2. Single-table = prefixes + overload.
  3. Collections cheap related reads.
  4. Link CRUD/CLI/SDK.

Revision, interview and comparison 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: Access patterns first. Keys invented before workloads cause Scans and hot partitions. List every read/write screen → shape Query → then PK/SK and optional GSI. Paper workshop → sample item JSON → peer review → console. Aisha Khan (Dubai retail) refuses new GSIs until access patterns are written.
Revision card: Access patterns first · Download PNG · Open card page
Revision card: Single-table sketch. One ER table per entity fights DynamoDB query shapes. Many entity types in one table with USER# / ORD# prefixes and overloaded SK. Entity list → PK/SK matrix → adjacency edges → prove with Query. Carlos Rivera sketches CartLite keys on a whiteboard before CDK.
Revision card: Single-table sketch · Download PNG · Open card page
Comparison: Single-table vs Multi-table. Single-table: Many entities, overloaded keys, fewer joins. Multi-table: Separate tables per domain/lifecycle.
Comparison: Single-table vs Multi-table · Download PNG · Open card page
Comparison: ER-first vs Access-first. ER-first: Normalize from ER then fight Scans. Access-first: List reads/writes then invent keys.
Comparison: ER-first vs Access-first · Download PNG · Open card page
Interview card: Why access patterns first?. Interview opener. Keys follow reads/writes; ER-first creates Scans. Name two patterns then invent one PK/SK.
Interview card: Why access patterns first? · Download PNG · Open card page
Interview card: What is single-table design?. Definition. Many entities one table; prefixes; Query not join. Say when a second table is still OK.
Interview card: What is single-table design? · Download PNG · Open card page
Interview card: Explain adjacency lists. Relationships. Edge items under a PK link entities for many-to-many. Give a student↔course example.
Interview card: Explain adjacency lists · Download PNG · Open card page
Interview card: Where is PutItem syntax?. No duplication. Linked CRUD/CLI/SDK chapters — this set models, not rewrites APIs. Name the three link targets.
Interview card: Where is PutItem syntax? · Download PNG · Open card page

More cards: Ravi Sir's Cards.

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

Maple Leaf Books is a bookselling business in Toronto. Emily Tremblay looks after its IT and cloud work. They count money in CAD and run their AWS resources in the ca-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 / 16

Easy Start the design with what the app must do

Before deciding how to store Users, Orders and Payments, list questions such as “show this customer’s last five orders.” What is that list called?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Name a mixed-entity table design

One DynamoDB table contains CART items and ORDER items, and their key values distinguish the entities. What is this modelling approach called?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Group only cart items under a user key

Under PK USER#u1, your cart sort keys start CART# and order sort keys start ORDER#. Which DynamoDB function in a Query key condition selects the CART# group?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Model many-to-many follows

A user can follow many others and be followed by many. Name the design pattern that stores each relationship as an item under a user’s partition key.

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Tiny access map YAML

Sketch.

YAML: patterns with get-user and list-orders-by-user.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Easy Choose the read operation for co-located items

A customer item and its addresses share one partition key. Which DynamoDB read operation retrieves a selected sort-key range from that partition?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Add a lookup by customer after designing order keys

The base table is keyed by order ID, but a new screen must find orders by customer ID. Name the index type that can introduce that alternate partition key.

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Name the group of items sharing a partition key

What does DynamoDB call the set of base-table and local secondary index items that share a particular partition-key value?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Support a date range under a customer partition

The app queries a customer’s events between two timestamps without changing the partition key. Which part of a composite primary key stores the ordering value?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Turn a diagram into a usable table design

An entity diagram shows relationships but does not tell you how a request will read or write data. What should you write down to fill that gap?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Separate an unrelated one-year audit store

An audit-log workload has different permissions and retention requirements from a checkout table. Which DynamoDB resource gives it an independent data lifecycle?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium User profile key sketch

Keys.

YAML: pk: USER#u1, sk: PROFILE.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Hard Insert the first sample item by API name

After drawing your sample CART item, which DynamoDB API writes one new item with an exact primary key?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Hard Translate one screen into a lookup

On paper, write the request “show user u42’s cart.” What value goes in the partition key under the illustrated USER# convention?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Hard Understand an overloaded sort key

A single index uses values such as ORDER#2026-11-21 and RETURN#2026-11-21 in its sort key. What part of the string separates the two types?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Hard Describe the key pair in a sample item

You write an ORDER item before coding. Its partition key is known and its table has a composite primary key. Which additional key attribute must its JSON contain?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.