Explain it simply
Explain it simply
In a relational database you store data neatly and figure out questions later with JOINs. DynamoDB flips this: you write down the questions first and arrange the data in advance so each answer comes back in one request. That is why these queries stay fast no matter how much data you add.
Single-table design keeps different entities, such as customers, orders and payments, in one table and builds the partition key (PK) and sort key (SK) from prefixed strings like 'CUSTOMER#123'. A customer and their orders share the same PK, so one Query returns them together. In AWS Fundamentals you created a simple table with one partition key; now we grow that into a production schema.
Problem → Why → Solution
The problem: using DynamoDB like a relational database
A team creates three tables, customers, orders and order_items, with each ID as the partition key. To show 'a customer's last ten orders', they GetItem the customer, Scan the orders table with a FilterExpression, then fetch items for each order.
It is fast with little data, but once there are millions of orders the Scan reads the whole table, and you pay for everything read before the filter is applied. A page load takes seconds and the read capacity bill climbs.
import boto3
from boto3.dynamodb.conditions import Attr
orders = boto3.resource("dynamodb", region_name="us-east-1").Table("orders")
def recent_orders(customer_id: str) -> list:
# Scan reads EVERY item in the table, then filters: cost grows with table size,
# not with the size of the answer. (Pagination is ignored here, too.)
resp = orders.scan(FilterExpression=Attr("customerId").eq(customer_id))
return sorted(resp["Items"], key=lambda o: o["createdAt"], reverse=True)[:10]Why this hurts
DynamoDB has no JOINs, and a Scan costs as much as the table is large. If the key design does not match the access patterns, you lose DynamoDB's main strength: predictable latency at any data size.
Core concept: from access patterns to keys
List the access patterns
Write down every read and write the application performs, such as 'get customer profile by ID', 'get a customer's orders by date' and 'get all pending orders', and note how often each runs.
Map entities onto keys
Give items that are read together the same PK, and build the SK in the shape you want to sort or filter by.
Cover the rest with GSIs
For patterns the base table keys cannot answer, add GSIs using generic attributes such as GSI1PK/GSI1SK.
- Item collection
- All items that share one partition key value, stored sorted by SK so one Query can read a range of them.
In the order example, the customer profile is stored at PK=CUSTOMER#123, SK=PROFILE, and orders at PK=CUSTOMER#123, SK=ORDER#2026-02-11#o-2. Putting the date in ISO format (YYYY-MM-DD) inside the SK makes string order equal time order, so begins_with(SK, 'ORDER#') selects only orders and between selects a date range. A Query returns up to 1 MB per page, and ScanIndexForward=false reads newest first.
GSI overloading means storing different meanings in the same GSI1PK/GSI1SK attributes depending on the entity type: STATUS#PENDING on an order, EMAIL#... on a customer, and so on. A few GSIs can then answer many patterns. A sparse index exploits the fact that only items carrying the GSI key attributes enter the index: set GSI1PK only on pending orders and the index stays small and cheap to read.
The real reason for one table is not having fewer tables. Grouping items of different entity types into one item collection lets the application fetch everything a page needs in a single request. An item can be at most 400 KB, so storing an order's line items as separate items is safer than one ever-growing list attribute.
ONE TABLE, SEVERAL ENTITIES
---------------------------
PK SK GSI1PK GSI1SK
--------------- ------------------------- -------------- ----------
CUSTOMER#123 PROFILE - -
CUSTOMER#123 ORDER#2026-01-05#o-1 - (shipped) -
CUSTOMER#123 ORDER#2026-02-11#o-2 STATUS#PENDING 2026-02-11
CUSTOMER#123 ORDER#2026-03-02#o-3 STATUS#PENDING 2026-03-02
EMAIL#mya@ex... EMAIL - -
|<--- item collection for CUSTOMER#123 --->| |<- sparse GSI1 ->|- Write the questions first
- Same PK for things read together
- Shape the SK for sorting and ranges
- Answer the rest with GSIs
A new access pattern may need a new GSI or a data backfill; that is the price of single-table design.
Creating a table with generic keys
cat > gsi.json <<'JSON'
[{"IndexName": "GSI1",
"KeySchema": [{"AttributeName": "GSI1PK", "KeyType": "HASH"},
{"AttributeName": "GSI1SK", "KeyType": "RANGE"}],
"Projection": {"ProjectionType": "ALL"}}]
JSON
aws dynamodb create-table --table-name shop \
--attribute-definitions AttributeName=PK,AttributeType=S \
AttributeName=SK,AttributeType=S \
AttributeName=GSI1PK,AttributeType=S AttributeName=GSI1SK,AttributeType=S \
--key-schema AttributeName=PK,KeyType=HASH AttributeName=SK,KeyType=RANGE \
--global-secondary-indexes file://gsi.json \
--billing-mode PAY_PER_REQUEST \
--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGESGeneric key attribute names (PK, SK, GSI1PK, GSI1SK) let you add new entity types without schema changes. Only key attributes go in attribute-definitions; everything else is schemaless.
Worked example: item collection, sparse GSI and a transaction
This script writes one customer and three orders into the shop table, adding GSI1 keys only to pending orders. It then answers two access patterns with Query and registers two customers with TransactWriteItems so that email stays unique.
import boto3
from boto3.dynamodb.conditions import Key
client = boto3.client("dynamodb", region_name="us-east-1")
table = boto3.resource("dynamodb", region_name="us-east-1").Table("shop")
# 1. Customer profile + orders share one partition: an item collection
table.put_item(Item={"PK": "CUSTOMER#123", "SK": "PROFILE", "name": "Aye Aye"})
orders = [
("2026-01-05#o-1", "SHIPPED", 40),
("2026-02-11#o-2", "PENDING", 75),
("2026-03-02#o-3", "PENDING", 18),
]
for date_id, status, total in orders:
item = {"PK": "CUSTOMER#123", "SK": "ORDER#" + date_id, "status": status,
"total": total}
if status == "PENDING": # sparse index: only pending orders get GSI1 keys
item["GSI1PK"] = "STATUS#PENDING"
item["GSI1SK"] = date_id
table.put_item(Item=item)
# Pattern: "customer 123's orders from February 2026 on, newest first"
resp = table.query(
KeyConditionExpression=Key("PK").eq("CUSTOMER#123")
& Key("SK").between("ORDER#2026-02", "ORDER#2026-99"),
ScanIndexForward=False,
)
print("recent orders:", [i["SK"] for i in resp["Items"]])
# Pattern: "all pending orders across customers", via the sparse GSI
resp = table.query(
IndexName="GSI1", KeyConditionExpression=Key("GSI1PK").eq("STATUS#PENDING")
)
print("pending (GSI1):", [i["GSI1SK"] for i in resp["Items"]])
# 2. New customer + unique email claim: both writes or neither
def register(customer_id: str, email: str) -> str:
def put_new(pk: str, sk: str, extra: dict) -> dict:
item = {"PK": {"S": pk}, "SK": {"S": sk}, **extra}
return {"Put": {"TableName": "shop", "Item": item,
"ConditionExpression": "attribute_not_exists(PK)"}}
try:
client.transact_write_items(TransactItems=[
put_new("CUSTOMER#" + customer_id, "PROFILE", {"email": {"S": email}}),
put_new("EMAIL#" + email, "EMAIL", {"customerId": {"S": customer_id}}),
])
return "created"
except client.exceptions.TransactionCanceledException as err:
reasons = [r["Code"] for r in err.response["CancellationReasons"]]
return "rejected " + str(reasons)
print("register 456:", register("456", "mya@example.com"))
print("register 789:", register("789", "mya@example.com"))Not runnable in the browser
This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.
Code breakdown
- Composite SK
"SK": "ORDER#" + date_idThe ORDER# prefix separates item types and the ISO date gives the sort order. The order ID after the date keeps SKs unique when two orders share a day.
- Range query
Key("SK").between("ORDER#2026-02", "ORDER#2026-99")This is a string comparison, so "ORDER#2026-99" sorts after every 2026 date. The PROFILE item is outside the range and not returned, and neither is o-1 from January.
- Sparse GSI
item["GSI1PK"] = "STATUS#PENDING"Shipped order o-1 has no GSI1PK, so it never enters the index. When an order ships, REMOVE GSI1PK and it drops out of the index automatically.
- Transaction
"ConditionExpression": "attribute_not_exists(PK)"DynamoDB has no unique constraint besides the key, so an EMAIL#... item acts as a lock. On the second registration the email item already exists, so the whole transaction is cancelled and CUSTOMER#789 is not written either. The reasons list shows each item's outcome in order.
recent orders: ['ORDER#2026-03-02#o-3', 'ORDER#2026-02-11#o-2']
pending (GSI1): ['2026-02-11#o-2', '2026-03-02#o-3']
register 456: created
register 789: rejected ['None', 'ConditionalCheckFailed']Adjacency lists and many-to-many
For many-to-many relationships, such as employees and projects, use the adjacency list pattern. Store each relationship as an item like PK=PROJECT#p1, SK=EMPLOYEE#e7, and copy the keys reversed into GSI1PK=EMPLOYEE#e7, GSI1SK=PROJECT#p1 (an inverted index). 'Employees on a project' then comes from the base table and 'projects for an employee' from the GSI, each with one Query.
The relationship item can hold edge data such as role and joinedAt, and teams often denormalize frequently read fields such as the employee's name into it. But a name change then means updating every relationship item, so copy only data that rarely changes.
Hot partitions and write sharding
One partition handles roughly 3,000 read capacity units and 1,000 write capacity units per second. Adaptive capacity automatically isolates busy keys, but writes to one single key still cannot exceed that limit. An election vote counter that receives thousands of writes per second on one key gets throttled.
Write sharding splits a key into N shards with a suffix. Writes spread across the shards, and reads fetch every shard and add them up. Deriving the suffix from a hash of the voter ID, rather than randomly, means you can always find which shard holds a given voter's item.
import hashlib
import boto3
table = boto3.resource("dynamodb", region_name="us-east-1").Table("votes")
SHARDS = 10
def shard_for(voter_id: str) -> int:
# Deterministic: the same voter always lands on the same shard
return int(hashlib.sha256(voter_id.encode()).hexdigest(), 16) % SHARDS
def cast_vote(candidate: str, voter_id: str) -> None:
table.update_item(
Key={"PK": f"CANDIDATE#{candidate}#SHARD#{shard_for(voter_id)}", "SK": "COUNT"},
UpdateExpression="ADD votes :one",
ExpressionAttributeValues={":one": 1},
)
def total_votes(candidate: str) -> int:
keys = [
{"PK": f"CANDIDATE#{candidate}#SHARD#{n}", "SK": "COUNT"} for n in range(SHARDS)
]
resp = table.meta.client.batch_get_item(RequestItems={"votes": {"Keys": keys}})
return sum(int(item["votes"]) for item in resp["Responses"]["votes"])
for i in range(200):
cast_vote("aung", f"voter-{i}")
print("shards used:", len({shard_for(f"voter-{i}") for i in range(200)}))
print("total votes:", total_votes("aung"))Capacity modes, conditional writes and Streams
| On-demand | Provisioned | |
|---|---|---|
| Billing | Per read/write request | Per capacity unit per hour |
| Best for | Unpredictable, spiky, new tables | Steady, predictable load |
| Scaling | Automatic | Auto scaling you configure |
A conditional write checks the item's current state before writing. For optimistic locking, keep a version number on the item and update with the condition 'version = :expected' while incrementing it; if another writer changed it first you get ConditionalCheckFailedException, then re-read and retry. TransactWriteItems writes up to 100 items all-or-nothing, but each item costs twice the capacity of a normal write.
DynamoDB Streams keeps every item change for 24 hours, in order per item. Connect it to a Lambda ESM to publish OrderPlaced events to EventBridge, update aggregate counters or index into OpenSearch. The application code only writes the table, and the stream handles the side effects.
In production
In production
Teams that succeed with single-table design keep the access pattern list and each entity's key shape in the repo, as a spreadsheet or a NoSQL Workbench model. Because generic names like PK/SK make code hard to read, they gather key builder functions (customer_pk(id), order_sk(date, id)) in one library and never hand-build key strings.
- Every item carries an entityType attribute, which makes exports, analytics and debugging easier.
- Ad-hoc analytics run outside DynamoDB, using S3 export with Athena or a zero-ETL integration.
- ThrottledRequests and CloudWatch Contributor Insights are used to watch for hot keys.
- Point-in-time recovery is enabled on every production table.
Most often each microservice owns its own table: 'single table' means one table per service's entities, not one table for the whole company. Other services read that data through the owning service's API or its stream events.
Common mistakes
Common mistakes
Mistake 1: a low-cardinality partition key
Using a status or a single date as the partition key (or GSI partition key) piles all traffic onto a few keys and creates a hot partition. The STATUS#PENDING GSI in this lesson is fine with a modest number of pending orders, but at thousands of writes per second it must be sharded, like STATUS#PENDING#0..9. A throttled GSI can also throttle writes to the base table.
Mistake 2: single-table design without known access patterns
During early product discovery, when queries change every week, every key design becomes a migration. In that situation, in apps heavy on ad-hoc reporting, or with modest data and an SQL-fluent team, Aurora/RDS or a simple one-table-per-entity layout is the better fit. Single-table design pays off at large scale with stable access patterns.
Mistake 3: assuming GSIs are strongly consistent
GSIs only support eventually consistent reads. Query a GSI right after writing an order and it may not be there yet. Answer read-after-write patterns with the base table keys.
💰 Cost & Cleanup
On-demand tables are billed per read/write request and storage per GB-month. Every GSI adds its own storage and write charges, so watch the cost of projection ALL. Transactions use twice the capacity per item. Reading Streams from a Lambda trigger is free, but the Lambda invocations are not. The free tier includes 25 GB of storage and some provisioned capacity (check the pricing page). This lab writes only a few items and costs cents, but delete the tables.
Clean up when you are done
aws dynamodb delete-table --table-name shop
aws dynamodb delete-table --table-name votes
aws dynamodb wait table-not-exists --table-name shopMini challenge
Mini challenge: add order line items
Add an order's line items to the table and design keys so that 'order o-2 with all its items' comes back in one Query.
- The customer's order list query (PK=CUSTOMER#123) must keep working unchanged
- The order header and its items must share one item collection (base table or GSI)
- One Query returns the header before the items
Expected: Querying GSI2 with GSI2PK=ORDER#o-2 returns the header item followed by ITEM#001 and ITEM#002, in that order.
Show hint
Store items at PK=ORDER#o-2, SK=ITEM#001, and overload the order header with GSI2PK=ORDER#o-2, GSI2SK=#HEADER. '#' sorts before digits and letters.
Show solution
import boto3
from boto3.dynamodb.conditions import Key
table = boto3.resource("dynamodb", region_name="us-east-1").Table("shop")
# Header stays in the customer's collection, and also joins the order's GSI2 group
table.put_item(Item={
"PK": "CUSTOMER#123", "SK": "ORDER#2026-02-11#o-2",
"GSI2PK": "ORDER#o-2", "GSI2SK": "#HEADER", "total": 75,
})
for n, sku in [("001", "tea-leaf"), ("002", "longyi")]:
table.put_item(Item={
"PK": "ORDER#o-2", "SK": "ITEM#" + n,
"GSI2PK": "ORDER#o-2", "GSI2SK": "ITEM#" + n, "sku": sku,
})
resp = table.query(IndexName="GSI2", KeyConditionExpression=Key("GSI2PK").eq("ORDER#o-2"))
print([i["GSI2SK"] for i in resp["Items"]])Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Start from the access pattern list and derive the key design from it.
- Read several entity types in one Query through item collections that share a PK.
- GSI overloading and sparse indexes answer many patterns with few GSIs.
- Handle hot keys with write sharding and uniqueness with transactions plus conditions.
- Skip single-table design when access patterns are not stable.
Best practices for designing with DynamoDB — AWS Documentation
DynamoDB transactions — AWS Documentation
DynamoDB Streams — AWS Documentation