DynamoDB Keys, Indexes and Capacity
Overview
Amazon DynamoDB is a fully managed NoSQL key-value and document database that delivers single-digit millisecond performance at any scale. You do not manage servers, patching or replicas; you design tables, keys and access patterns, and DynamoDB takes care of distribution.
Imagine a giant filing warehouse. The partition key tells the clerk which aisle to walk to, and the sort key orders folders on the shelf in that aisle. If you know the aisle and folder you can fetch it instantly (Query/GetItem). If you do not, someone has to walk every aisle (Scan), which is slow and costly.
The exam loves DynamoDB: key design, choosing Query over Scan, capacity calculations, indexes, conditional writes and throttling.
Key Concepts
- A table needs a primary key: partition key alone (simple) or partition key + sort key (composite). Items are max 400 KB.
- Query reads items with one partition key value (optionally filtered by sort key); Scan reads the whole table and should be avoided.
- GSI (global secondary index): different partition/sort keys, eventually consistent, own capacity, can be added any time; up to 20 per table by default.
- LSI (local secondary index): same partition key, different sort key, must be created with the table, supports strong consistency, shares table capacity; limit 5; 10 GB per partition key.
- Capacity modes: provisioned (RCU/WCU, auto scaling) and on-demand (pay per request).
- 1 RCU = one strongly consistent read/s of up to 4 KB (or two eventually consistent); 1 WCU = one write/s of up to 1 KB; transactional ops cost double.
- Conditional expressions enable optimistic locking and prevent overwrites; ProjectionExpression returns only chosen attributes.
- TTL deletes expired items for free using an epoch-seconds attribute; deletion typically happens within days.
Detailed Notes
Choosing keys
High-cardinality partition keys spread load evenly. A bad key (such as a status flag or date) creates a hot partition and throttling, even if table-level capacity is sufficient.
| Pattern | Key design |
|---|---|
| User orders | PK = USER#123, SK = ORDER#2025-03-01#789 |
| Many-to-many | Adjacency list with a GSI that inverts PK/SK |
| Write-heavy counter | Add a random write sharding suffix to the PK |
Capacity calculations
- Writes: item size rounded up to 1 KB. 10 items/s of 2.5 KB = 10 x 3 = 30 WCU.
- Strongly consistent reads: size rounded up to 4 KB. 10 reads/s of 6 KB = 10 x 2 = 20 RCU.
- Eventually consistent: half, so 10 RCU.
- Transactional reads/writes use 2x.
Python: put, get, query
import boto3
from boto3.dynamodb.conditions import Key
table = boto3.resource("dynamodb").Table("Orders")
table.put_item(
Item={"pk": "USER#123", "sk": "ORDER#2025-03-01#789", "total": 4200},
ConditionExpression="attribute_not_exists(pk)", # no overwrite
)
resp = table.query(
KeyConditionExpression=Key("pk").eq("USER#123") & Key("sk").begins_with("ORDER#2025"),
ProjectionExpression="sk, total",
ScanIndexForward=False, # newest first
Limit=25,
)
items = resp["Items"]
last = resp.get("LastEvaluatedKey") # use as ExclusiveStartKey for next page
import { DynamoDBDocumentClient, UpdateCommand } from "@aws-sdk/lib-dynamodb";
await doc.send(new UpdateCommand({
TableName: "Orders",
Key: { pk: "USER#123", sk: "ORDER#2025-03-01#789" },
UpdateExpression: "SET #s = :new, version = version + :one",
ConditionExpression: "version = :expected",
ExpressionAttributeNames: { "#s": "status" },
ExpressionAttributeValues: { ":new": "SHIPPED", ":one": 1, ":expected": 3 },
}));
A failed condition raises ConditionalCheckFailedException. This is optimistic locking.
Query vs Scan
| Query | Scan | |
|---|---|---|
| Needs partition key | Yes | No |
| Reads | Only matching items | Entire table |
| Cost | Low | High; filter applied after reading |
| Pagination | LastEvaluatedKey | LastEvaluatedKey |
FilterExpression runs after items are read, so you still pay for the reads. If you must scan, use parallel scan (Segment, TotalSegments) and rate limit.
Indexes
| GSI | LSI | |
|---|---|---|
| Keys | Any attributes | Same PK, different SK |
| Consistency | Eventual only | Eventual or strong |
| Capacity | Separate | Shared with table |
| Create | Anytime | Only at table creation |
Writes to a GSI are asynchronously replicated; if a GSI lacks write capacity it throttles writes to the base table. Project only needed attributes (KEYS_ONLY, INCLUDE, ALL).
Throttling and hot keys
ProvisionedThroughputExceededException means requests exceed capacity. Use backoff, on-demand mode, auto scaling, better key distribution, or DAX for read-heavy hot items. Adaptive capacity shifts capacity to hot partitions but cannot fix a single key's limit of 3,000 RCU / 1,000 WCU per partition.
Capacity modes
| Mode | Best for |
|---|---|
| On-demand | Unpredictable or spiky traffic, new tables |
| Provisioned + auto scaling | Steady, predictable traffic; cheaper per request |
| Reserved capacity | Long-term provisioned commitments |
Table definition (SAM)
OrdersTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- { AttributeName: pk, AttributeType: S }
- { AttributeName: sk, AttributeType: S }
- { AttributeName: gsi1pk, AttributeType: S }
KeySchema:
- { AttributeName: pk, KeyType: HASH }
- { AttributeName: sk, KeyType: RANGE }
GlobalSecondaryIndexes:
- IndexName: gsi1
KeySchema: [{ AttributeName: gsi1pk, KeyType: HASH }]
Projection: { ProjectionType: ALL }
TimeToLiveSpecification: { AttributeName: expiresAt, Enabled: true }
Query, Scan and expressions
| Operation | Reads | Cost | Notes |
|---|---|---|---|
| GetItem | One item by full key | 1 RCU per 4 KB strongly consistent (0.5 eventually) | Fastest |
| Query | Items in one partition, optionally filtered by sort key | Charged on data read, not returned | Needs the partition key; use begins_with, between on sort key |
| Scan | Whole table or index | Reads every item, then filters | Avoid in hot paths; parallel scan with Segment/TotalSegments |
A FilterExpression is applied after the read, so it reduces the response size but not consumed capacity. Responses are capped at 1 MB; follow LastEvaluatedKey as ExclusiveStartKey to paginate.
from boto3.dynamodb.conditions import Key, Attr
resp = table.query(
KeyConditionExpression=Key("pk").eq("CUSTOMER#42") & Key("sk").begins_with("ORDER#2025"),
FilterExpression=Attr("status").eq("OPEN"),
ProjectionExpression="sk, #s, total",
ExpressionAttributeNames={"#s": "status"}, # status is a reserved word
ConsistentRead=True,
Limit=25)
items, token = resp["Items"], resp.get("LastEvaluatedKey")
Capacity maths
One WCU writes 1 KB per second, one RCU reads 4 KB strongly consistent (or two eventually consistent) per second, and a transactional read or write costs double. Example: 100 strongly consistent reads per second of 6 KB items needs 100 x 2 = 200 RCU, because 6 KB rounds up to 8 KB (two 4 KB units). On-demand mode removes planning at a higher unit price; provisioned mode with auto scaling suits predictable load. Each partition handles about 3,000 RCU and 1,000 WCU, so a hot key throttles even when the table has spare capacity.
Writes that are safe to retry
Use ConditionExpression for optimistic locking (a version attribute) and UpdateExpression atomic counters (ADD views :one). A failed condition returns ConditionalCheckFailedException, which is a business outcome, not a transient error. Items are limited to 400 KB, so keep large blobs in S3 and store a pointer.
Real World Example
A gaming company stored leaderboards with the partition key gameId. During a tournament one game received most of the traffic, causing hot-partition throttling although the table had ample capacity. They redesigned with write sharding (gameId#shard0-9), queried all ten shards in parallel and merged results, and switched to on-demand capacity for the event. Throttling disappeared, and expired sessions were cleaned up for free with TTL.
Architecture Diagram
Queries hit the base table by key or a GSI for alternate access patterns.
- 1The application builds a key from its access pattern.
- 2Query reads items in one partition, ordered by the sort key.
- 3A GSI serves queries on alternate attributes.
- 4Metrics reveal throttling and hot partitions.
Best Practices
- ✓Design keys from access patterns first; keep partition keys high-cardinality.
- ✓Use Query, never Scan, in request paths.
- ✓Use conditional writes for uniqueness and optimistic locking.
- ✓Project only required attributes into GSIs and give them enough capacity.
- ✓Enable TTL for expiring data and point-in-time recovery for backups.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Throttling on a table with spare capacity -> hot partition; fix the key.
- LSI must be created at table creation; GSIs can be added later.
- Reduce cost of reading few attributes -> ProjectionExpression (does not reduce RCU) vs index projection (does).
- Do the RCU/WCU rounding carefully: 4 KB reads, 1 KB writes.
Finished this lesson?
0 of 46 lessons done · 0% of the course

