Overview and What You Will Learn
Amazon DynamoDB is a fully managed, serverless NoSQL database that returns reads and writes in single-digit milliseconds at almost any scale. It is Multi-AZ by default and has no servers, patching or capacity planning to manage in On-Demand mode. In this lab you design a table around its access patterns, pick a capacity mode, and then enable TTL, Streams and point-in-time recovery from the AWS CLI.
By the end you will be able to:
- Decide when DynamoDB is the right database and when RDS is a better fit
- Model tables, items and attributes, and choose between a simple and a composite primary key
- Pick a high-cardinality partition key that avoids hot partitions
- Choose between On-Demand and Provisioned capacity, and read RCU and WCU numbers correctly
- Add Global Secondary Indexes for access patterns the primary key cannot serve
- Use DAX for microsecond cached reads, Streams for event-driven pipelines, and Global Tables for multi-region writes
- Expire data automatically with TTL and protect it with PITR, on-demand backups and S3 export
Why This Matters in Production
A video streaming platform such as Hotstar needs to fetch episode metadata by video ID millions of times per second, and a relational database would need heavy sharding and caching to keep up. A fintech such as Razorpay or PhonePe needs session tokens that expire on their own after a few minutes and a schema that gains new attributes every sprint without migrations. DynamoDB fits these shapes because the access pattern is simple and known in advance, the scale is large, and the schema changes often.
It is also easy to misuse. A low-cardinality partition key throttles one partition while the rest sit idle, and a Scan on a large table burns read capacity and money. Getting the key design right on day one matters because the primary key cannot be changed after the table is created.
Core Principles
When Should You Use DynamoDB Instead of RDS?
Use DynamoDB when you know your access patterns up front, access data mostly by key, need predictable low latency at large scale, and expect the schema to evolve. Use RDS when you need ad-hoc SQL, joins across many entities, or heavy reporting and aggregation. DynamoDB does support transactions (TransactWriteItems and TransactGetItems, up to 100 items per call, across tables), but it is not a replacement for a relational model with complex relationships.
| Choose DynamoDB when | Choose RDS when |
|---|---|
| Access is mostly by key | You need SQL joins |
| Scale is large and spiky | You run ad-hoc reporting |
| Schema changes often | Entities are highly relational |
| You need multi-region writes | You need rich constraints |
How Do Tables, Items, and Attributes Work?
A table is a named container, an item is one record (up to 400 KB), and an attribute is one field on an item. The only attributes every item must have are the ones in the primary key. Every other attribute is optional and can differ from item to item, which is why new features can add new attributes without a migration.
Item 1: UserId=1, Name=Rahul, Email=rahul@devops.in, Age=25Item 2: UserId=2, Name=Priya, Phone=9876543210, City=PuneItem 3: UserId=3, Name=Arjun, Score=99, Badges=[gold, silver]Supported data types fall into three groups: scalar (String, Number, Binary, Boolean, Null), document (List, Map) and set (String Set, Number Set, Binary Set).
How Do You Choose a DynamoDB Primary Key?
The primary key uniquely identifies each item and is fixed at table creation. A simple key is a partition key alone, so one item per key value. A composite key is a partition key plus a sort key, so one partition key can own many items ordered by the sort key, and you can query them as a range.
| UserId (partition) | GameId (sort) | Score |
|---|---|---|
| user-001 | game-42 | 92 |
| user-002 | game-18 | 14 |
| user-002 | game-42 | 77 |
user-002 appears twice because each UserId plus GameId pair is unique. This is how one table stores a one-to-many relationship without a join.
How Do You Pick a Partition Key That Avoids Hot Partitions?
Pick an attribute with many distinct values that your traffic spreads across evenly, such as UserId, OrderId or DeviceId. DynamoDB hashes the partition key value to decide which physical partition stores the item, so a key with few values or one dominant value concentrates traffic on a single partition and causes throttling.
- Good keys: UserId, OrderId, DeviceId, a random session token
- Bad keys: Status, Country, a boolean flag, or today's date, because most writes share one value
Common MistakeUsing a low-cardinality attribute such as Status or Country as the partition key. If 90 percent of writes carry Status=active, 90 percent of writes hit one partition and get throttled. Choose a high-cardinality attribute, or add a random or calculated suffix to the key (write sharding) to spread a hot key.
What Is the Difference Between On-Demand and Provisioned Capacity?
On-Demand mode scales reads and writes automatically and bills per request, so there is nothing to plan and no throttling from under-provisioning. Provisioned mode makes you set read capacity units (RCU) and write capacity units (WCU) in advance, which is cheaper for steady traffic but throttles if you set it too low. You can switch modes, but only once every 24 hours.
- 1 RCU is one strongly consistent read per second for an item up to 4 KB, or two eventually consistent reads
- 1 WCU is one write per second for an item up to 1 KB
- Provisioned mode can use Auto Scaling to follow traffic within limits you set
| Provisioned | On-Demand | |
|---|---|---|
| Capacity planning | Required | None |
| Best for | Steady, predictable load | New or spiky load |
| Throttling risk | If under-provisioned | Rare |
TipStart new tables On-Demand. After a few weeks of real traffic, move steady tables to Provisioned with Auto Scaling if the numbers justify it.
How Do Secondary Indexes Work in DynamoDB?
A secondary index lets you query by an attribute that is not the table's primary key. A Global Secondary Index (GSI) has its own partition and sort key, can be added or removed at any time, and is eventually consistent. A Local Secondary Index (LSI) shares the table's partition key but has a different sort key, must be created with the table, and limits each partition key to 10 GB of data.
- Use a GSI when you need a new access pattern, such as "all orders for a city"
- Use an LSI only when you need a second sort order within the same partition key
- Query an index with the same Query API as the table
What Is Eventually Consistent vs Strongly Consistent Reading?
By default reads are eventually consistent, meaning a read right after a write might return the previous value for a short time. Strongly consistent reads return the latest committed value but cost twice the read capacity and are not available on GSIs or across Global Table regions. Use strong consistency only where stale data would cause a wrong decision.
What Is DAX and When Should You Use It?
DAX (DynamoDB Accelerator) is a fully managed in-memory cache built only for DynamoDB that serves repeated reads in microseconds instead of milliseconds. It speaks the DynamoDB API, so you point the SDK at the DAX cluster endpoint and leave the rest of the code unchanged. The first read is a cache miss that goes to DynamoDB, and later reads of the same item are served from memory.
Old endpoint: dynamodb.ap-south-1.amazonaws.comNew endpoint: devops-dax.abc123.dax-clusters.ap-south-1.amazonaws.comUse DAX for read-heavy hot items such as a leaderboard or product catalog. Use ElastiCache instead when you need to cache computed results that DynamoDB cannot produce, such as an aggregation across many items.
What Are DynamoDB Streams?
DynamoDB Streams records every create, update and delete on a table as an ordered change event kept for 24 hours. A Lambda function can subscribe to the stream so downstream work runs on every change without polling. For longer retention or more consumers, send table changes to Kinesis Data Streams, which can keep data for up to a year.
How Do DynamoDB Global Tables Work?
Global Tables replicate a table across AWS Regions with active-active replication, so every replica accepts writes and changes copy to the others, usually within about a second. A user in Mumbai reads and writes the Mumbai replica while a user in Virginia uses the Virginia replica, each with local latency. Streams with new and old images must be on for replication, and the console enables this for you when you add a replica.
RememberGlobal Tables resolve conflicts with last-writer-wins. If two Regions update the same item at nearly the same moment, one write is silently lost. Route each item's writes to one home Region where you can, or use conditional writes to detect conflicts.
How Does DynamoDB TTL Work?
TTL deletes items automatically once a timestamp you store on each item has passed. You enable TTL once on the table, name the attribute (for example ExpTime), and write a Number holding a Unix epoch time in seconds. Deletion is free and does not use write capacity, but it is not instant: expired items are usually removed within a few days, so filter expired items out in your queries if exactness matters.
- Good fits: session tokens, one-time codes, cache entries
- Keep durable data such as user profiles in a different table with no TTL, so only the session row expires
How Do You Back Up and Recover a DynamoDB Table?
Point-in-time recovery (PITR) continuously backs up the table and lets you restore to any second within a window of up to 35 days, creating a new table and leaving the original untouched. On-demand backups are full snapshots kept until you delete them, and AWS Backup can copy them across Regions. You can also export table data to S3 for Athena without using any read capacity, which requires PITR to be on.
Common MistakeAssuming PITR is on by default. It is not. Enable it on every production table when you create it, because an accidental bulk delete cannot be undone without it.
Detailed Step-by-Step Practical Lab
This lab uses the AWS CLI in ap-south-1. Commands use the CLI shorthand syntax so no JSON files are needed.
Step 1: Create the table
aws dynamodb create-table \ --table-name GameScores \ --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameId,AttributeType=S \ --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameId,KeyType=RANGE \ --billing-mode PAY_PER_REQUEST \ --region ap-south-1 # Wait until the table is ACTIVEaws dynamodb wait table-exists --table-name GameScores --region ap-south-1Step 2: Add items
# Two items for the same user with different sort keysaws dynamodb put-item --table-name GameScores --region ap-south-1 \ --item 'UserId={S=rahul-001},GameId={S=game-42},Score={N=92},Result={S=Win}' aws dynamodb put-item --table-name GameScores --region ap-south-1 \ --item 'UserId={S=rahul-001},GameId={S=game-18},Score={N=45},Result={S=Lose}'Step 3: Query one user instead of scanning
# Query reads only the items for one partition key valueaws dynamodb query --table-name GameScores --region ap-south-1 \ --key-condition-expression "UserId = :u" \ --expression-attribute-values ':u={S=rahul-001}'Both items come back. A Scan would read every item in the table and filter afterwards, so avoid it in production code.
Step 4: Enable TTL and add an expiring item
aws dynamodb update-time-to-live --table-name GameScores --region ap-south-1 \ --time-to-live-specification "Enabled=true,AttributeName=ExpTime" # Expiry timestamp 10 minutes from now, in epoch secondsEXP=$(date -d "+10 minutes" +%s) aws dynamodb put-item --table-name GameScores --region ap-south-1 \ --item "UserId={S=rahul-001},GameId={S=session-temp},ExpTime={N=$EXP}"DynamoDB removes the item after it expires, usually within a few days rather than at the exact second. Until then, add a filter on ExpTime if your query must never return it.
Step 5: Enable Streams and PITR
aws dynamodb update-table --table-name GameScores --region ap-south-1 \ --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES aws dynamodb update-continuous-backups --table-name GameScores --region ap-south-1 \ --point-in-time-recovery-specification PointInTimeRecoveryEnabled=trueStep 6: Export to S3 for analytics
# Requires PITR to be enabled; does not consume read capacityaws dynamodb export-table-to-point-in-time \ --table-arn arn:aws:dynamodb:ap-south-1:123456789012:table/GameScores \ --s3-bucket devops-analytics-exports \ --s3-prefix dynamodb-exports/ \ --export-format DYNAMODB_JSON \ --region ap-south-1Step 7: Clean up
aws dynamodb delete-table --table-name GameScores --region ap-south-1Production Best Practices & Common Pitfalls
- Design from access patterns: List the queries your application runs first, then pick keys and indexes to serve them. Retrofitting is painful because the primary key is fixed.
- Choose a high-cardinality partition key: It sets the performance ceiling for the whole table.
- Use Query, not Scan: Scan reads every item and gets slower and costlier as the table grows.
- Enable PITR on every production table from day one: It is off by default.
- Start On-Demand: Move steady workloads to Provisioned with Auto Scaling once traffic is predictable.
- Keep items small: The limit is 400 KB per item. Store large objects in S3 and keep only the S3 key in DynamoDB.
- Use TTL for naturally expiring data: It costs nothing and removes cleanup jobs, but do not rely on exact-second deletion.
- Plan for conflicts in Global Tables: Last-writer-wins can drop a concurrent write.
- Do not pick DynamoDB for everything: A trading ledger that needs relational integrity and ad-hoc reporting belongs in a relational database.
Common MistakeTreating DynamoDB like SQL and planning to "figure out the queries later". Without a matching key or index, the only option is a Scan.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| List tables | aws dynamodb list-tables --region ap-south-1 |
| Describe a table | aws dynamodb describe-table --table-name GameScores |
| Get one item | aws dynamodb get-item --table-name GameScores --key 'UserId={S=rahul-001},GameId={S=game-42}' |
| Delete one item | aws dynamodb delete-item --table-name GameScores --key 'UserId={S=rahul-001},GameId={S=game-42}' |
| Check TTL status | aws dynamodb describe-time-to-live --table-name GameScores |
| Check PITR status | aws dynamodb describe-continuous-backups --table-name GameScores |
| Problem | Likely cause and fix |
|---|---|
| ProvisionedThroughputExceededException | Under-provisioned capacity or a hot partition. Switch to On-Demand or redesign the key. |
| Item size exceeded | Item is over 400 KB. Move large attributes to S3. |
| Global Table setup fails | Streams with new and old images is not enabled. Enable it, then add the replica. |
| Query returns nothing | Key value or expression syntax does not match exactly. Check names and types. |
| TTL items still visible | Deletion is not instant. Filter on the TTL attribute, and confirm it is a Number in epoch seconds. |
| Scan is throttled | Replace with Query or add a GSI for that access pattern. |