DynamoDB Indexes, Capacity Modes, Throttling, TTL, Streams and DAX
Secondary Indexes
A table supports queries on its primary key. To query another way (for example orders by status), add an index.
| Global Secondary Index (GSI) | Local Secondary Index (LSI) | |
|---|---|---|
| Keys | Different partition key and optional sort key | Same partition key as the table, different sort key |
| Create | Any time | Only when creating the table |
| Capacity | Has its own RCU/WCU (or on-demand) | Shares the table capacity |
| Consistency | Eventually consistent only | Strong or eventual |
| Size limit | None special | 10 GB per partition key value (item collection limit) |
| Count | Up to 20 by default per table | Up to 5 |
bash
aws dynamodb update-table --table-name Orders \
--attribute-definitions AttributeName=status,AttributeType=S AttributeName=createdAt,AttributeType=S \
--global-secondary-index-updates '[{"Create":{"IndexName":"status-createdAt-index",
"KeySchema":[{"AttributeName":"status","KeyType":"HASH"},{"AttributeName":"createdAt","KeyType":"RANGE"}],
"Projection":{"ProjectionType":"INCLUDE","NonKeyAttributes":["total","customerId"]}}}]'
python
r = table.query(IndexName="status-createdAt-index",
KeyConditionExpression=Key("status").eq("PENDING") & Key("createdAt").gt("2026-11-01"))
| Projection | Contains |
|---|---|
KEYS_ONLY | Index and table keys only |
INCLUDE | Keys plus chosen attributes |
ALL | Everything (largest and costliest) |
- A GSI is a copy of data, so writes to the table also write to the index and use index write capacity. If a GSI is under-provisioned it can throttle the base table writes
- Only items that have the index key attributes appear in the index (a sparse index is a useful trick: put the attribute only on items you want to find)
- Querying attributes not projected into an LSI fetches from the table; a GSI cannot fetch them
Capacity Modes
| Mode | How it works | Choose when |
|---|---|---|
| On-demand | Pay per request. Scales instantly to previous peaks and beyond (it can double the previous peak quickly) | New or unpredictable traffic, spiky load, no planning |
| Provisioned | You set read and write capacity units. Can use auto scaling. Cheaper for steady, predictable load. Reserved capacity gives extra discounts | Stable traffic you can forecast |
RCU and WCU Calculations (Exam Favorite)
| Unit | Meaning |
|---|---|
| 1 WCU | One write per second of an item up to 1 KB (round up) |
| 1 RCU | One strongly consistent read per second of up to 4 KB (round up). Eventually consistent = half. Transactional read = double |
| 1 WRU / RRU | On-demand write and read request units follow the same sizes |
text
Example 1: 10 writes/second of 2.5 KB items
size 2.5 KB -> round up to 3 KB -> 3 WCU per write
10 x 3 = 30 WCU
Example 2: 80 strongly consistent reads/second of 6 KB items
6 KB / 4 KB = 1.5 -> round up to 2 RCU per read
80 x 2 = 160 RCU
Example 3: same reads but eventually consistent
160 / 2 = 80 RCU
Example 4: 50 transactional writes/second of 1 KB items
transactional write costs double: 50 x 1 x 2 = 100 WCU
Throttling and Hot Partitions
- When you exceed capacity DynamoDB returns **
ProvisionedThroughputExceededException(HTTP 400). The SDK retries with backoff**. Persistent throttling means you need more capacity, better key design or caching - Data and traffic are spread across partitions by key hash. A partition handles up to about 3,000 RCU and 1,000 WCU. A hot key (one celebrity user, one status value) overloads a single partition even if the table total looks fine
- DynamoDB provides burst capacity and adaptive capacity to help, but good keys matter most
| Fix for hot keys | How |
|---|---|
| High-cardinality partition key | Use userId or orderId instead of status or date |
| Write sharding | Add a random suffix status#0..9 and query all shards (scatter-gather) |
| Caching | DAX or ElastiCache for read-heavy hot items |
| Queue writes | SQS to smooth bursts |
| Use exponential backoff | Already built in to SDKs |
Time to Live (TTL)
- Pick a numeric attribute holding an epoch time in seconds. Items past that time are deleted in the background (usually within a few days, often much sooner) at no write cost
- Expired items may still appear in reads until deleted. Filter them in queries if exactness matters
- Deletions appear in Streams so you can archive them to S3
- Use for sessions, temporary tokens, caches and old logs
python
import time
table.put_item(Item={"pk": "session#abc", "user": "C-100", "expiresAt": int(time.time()) + 3600})
# enable once:
# aws dynamodb update-time-to-live --table-name Sessions --time-to-live-specification Enabled=true,AttributeName=expiresAt
DynamoDB Streams
- An ordered, 24-hour log of item changes:
KEYS_ONLY,NEW_IMAGE,OLD_IMAGEorNEW_AND_OLD_IMAGES - Order is guaranteed per item (per key)
- Process with Lambda (event source mapping), Kinesis adapter or EventBridge Pipes
- Uses: audit trail, sync to OpenSearch, send notifications, update aggregates, replicate, cache invalidation
python
from boto3.dynamodb.types import TypeDeserializer
td = TypeDeserializer()
def handler(event, context):
for rec in event["Records"]:
if rec["eventName"] == "INSERT":
new = {k: td.deserialize(v) for k, v in rec["dynamodb"]["NewImage"].items()}
print("new order", new["orderId"])
Failure behavior: If your Lambda throws an error for a stream batch, Lambda retries the same batch and blocks that shard until success or the data expires. Set max retry attempts, bisect on error and an on-failure destination.
DynamoDB Accelerator (DAX)
- A fully managed in-memory cache for DynamoDB giving microsecond reads, in your VPC. You use the DAX client with almost the same API
- Best for read-heavy, repeated reads of the same items (eventually consistent). Not for strongly consistent reads (they pass through) or write-heavy loads
- Has an item cache (GetItem/BatchGetItem) and a query cache (Query/Scan results). Default TTL 5 minutes
- Compare with ElastiCache: use ElastiCache when you cache computed results or non-DynamoDB data, DAX when you want a drop-in cache for DynamoDB
Other Useful Features
| Feature | Purpose |
|---|---|
| Point-in-time recovery (PITR) | Restore to any second in the last 35 days |
| On-demand backups / AWS Backup | Full backups without affecting performance |
| Global tables | Multi-Region, multi-active replication |
| Export to S3 / import from S3 | Move data without using table capacity |
| Standard-IA table class | Cheaper storage for rarely accessed tables |
| Encryption | Always on at rest (AWS owned, AWS managed or customer managed KMS key) |
Practice Tasks
- Add a GSI on status and createdAt and query pending orders
- Calculate RCU and WCU for three workloads using the formulas
- Create a provisioned table with 1 WCU and trigger throttling with a loop
- Enable TTL on a session table and watch an expired item disappear
- Enable a stream and print every INSERT from a Lambda function
Conclusion
Use GSIs for new query patterns (any time, own capacity, eventual reads) and LSIs only at table creation. Pick on-demand for unpredictable load and provisioned for steady load, calculate RCU/WCU by rounding item size up, design keys to avoid hot partitions, use TTL for expiry, Streams for change events and DAX for microsecond reads.
Quick Summary: GSI vs LSI; capacity modes; RCU/WCU math; throttling and hot keys; TTL; Streams; DAX; other features.

