Skip to content

DynamoDB

Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability .

Designed to run high-performance applications at any scale, handling trillions of requests per day while maintaining single-digit millisecond latency.


Amazon DynamoDB is a fully managed NoSQL database service that supports both key-value and document data models . Unlike traditional relational databases, DynamoDB is schemaless and designed for horizontal scaling, allowing you to store and retrieve any amount of data with consistent, single-digit millisecond latency at any scale .

BenefitDescription
Fully ManagedNo servers to provision, patch, or manage—AWS handles everything
Automatic ScalingScales throughput and storage automatically based on traffic patterns
Single-Digit Millisecond LatencyConsistent low-latency performance at any scale
ServerlessNo infrastructure management; pay only for what you use
High AvailabilityData is automatically replicated across multiple Availability Zones
ACID TransactionsSupport for atomic, consistent, isolated, and durable transactions across multiple items and tables
Flexible Data ModelSupports both key-value and document data models with nested attributes up to 32 levels deep

Understanding the basic building blocks of DynamoDB is essential .

ComponentDescriptionAnalogy
TableA collection of data; the container for your itemsSimilar to a table in a relational database
ItemA group of attributes uniquely identifiable by a primary key; each item represents one entitySimilar to a row or record
AttributeA fundamental data element; a key-value pair within an itemSimilar to a field or column

Here’s how data is structured in DynamoDB :

{
"PersonID": 101,
"LastName": "Smith",
"FirstName": "Fred",
"Phone": "555-4321"
}
{
"PersonID": 102,
"LastName": "Jones",
"FirstName": "Mary",
"Address": {
"Street": "123 Main",
"City": "Anytown",
"State": "OH",
"ZIPCode": 12345
}
}
{
"PersonID": 103,
"LastName": "Stephens",
"FirstName": "Howard",
"Address": {
"Street": "123 Main",
"City": "London",
"PostalCode": "ER3 5K8"
},
"FavoriteColor": "Blue"
}

Key observations about this example :

  • Each item has a unique identifier (primary key) called PersonID
  • The table is schemaless—items can have different attributes
  • Nested attributes (like Address) are supported up to 32 levels deep
  • Scalar attributes (strings, numbers) can have only one value

A table with a composite primary key :

{
"Artist": "No One You Know",
"SongTitle": "My Dog Spot",
"AlbumTitle": "Hey Now",
"Price": 1.98,
"Genre": "Country",
"CriticRating": 8.4
}
{
"Artist": "The Acme Band",
"SongTitle": "Still in Love",
"AlbumTitle": "The Buck Starts Here",
"Price": 2.47,
"Genre": "Rock",
"PromotionInfo": {
"RadioStationsPlaying": ["KHCR", "KQBX", "WTNR", "WJJH"],
"TourDates": {
"Seattle": "20150622",
"Cleveland": "20150630"
}
}
}

When you create a table, you must specify a primary key that uniquely identifies each item .

Key TypeComponentsDescriptionExample
Simple Primary Key (Partition Key)1 attributeDynamoDB uses the partition key as input to a hash function to determine storage partition. No two items can have the same partition key value.PersonID in People table
Composite Primary Key (Partition Key + Sort Key)2 attributesItems with the same partition key are stored together, sorted by sort key. Multiple items can have the same partition key but different sort keys.Artist (partition) + SongTitle (sort) in Music table
  • Partition Key = Hash attribute (due to internal hash function)
  • Sort Key = Range attribute (items with same partition key are stored physically close in sorted order)

Secondary indexes let you query data using an alternate key .

Index TypeDescriptionKey Difference
Global Secondary Index (GSI)Index with partition and sort keys that can be different from the tableCan span the entire table; keys don’t need to be unique
Local Secondary Index (LSI)Index with the same partition key as the table but a different sort keyMust be created when the table is created

Limits: Up to 20 GSIs (default quota) and 5 LSIs per table .

Example Use Case: In the Music table, you can query by Artist (partition key) or by Artist and SongTitle. To query by Genre and AlbumTitle, create a GSI with Genre as partition key and AlbumTitle as sort key .


4. Capacity Modes: On-Demand vs. Provisioned

Section titled “4. Capacity Modes: On-Demand vs. Provisioned”

DynamoDB offers two capacity modes .

FeatureOn-Demand ModeProvisioned Mode
Capacity PlanningNot required—scales automaticallyYou specify read/write capacity units
Best ForUnpredictable workloads, new applicationsPredictable workloads, cost optimization
ScalingInstant; adapts to any previously reached traffic levelAuto-scaling adjusts within min/max limits
PricingPay per requestPay per provisioned unit per hour
Cost at High VolumeMore expensiveCheaper with reserved capacity

Provisioned Mode Units :

UnitDefinition
Read Capacity Unit (RCU)One strongly consistent read per second for an item up to 4 KB
Write Capacity Unit (WCU)One write per second for an item up to 1 KB

On-Demand Mode Pricing Factors :

  • Write request units: up to 1 KB per write
  • Read request units: up to 4 KB per read
  • Transactional reads/writes consume 2 units each

5. Step-by-Step: Creating Your First DynamoDB Table

Section titled “5. Step-by-Step: Creating Your First DynamoDB Table”
  • AWS account
  • AWS Management Console access
  1. Sign in to AWS Console
  2. Navigate to DynamoDB (type in search bar)
  1. Click Create table
  2. Enter Table name (e.g., Music)
  3. Configure Partition key (e.g., Artist as String)
  4. Configure Sort key (optional, e.g., SongTitle as String)
  5. Choose Default settings or Customize settings

For on-demand mode:

  • Select On-demand under Capacity settings

For provisioned mode:

  • Select Provisioned
  • Enter read and write capacity units
  • Enable Auto scaling with target utilization (e.g., 70%)

Step 4: Configure Additional Settings (Optional)

Section titled “Step 4: Configure Additional Settings (Optional)”
SettingOptionsWhen to Use
Secondary indexesGSI or LSIAdd alternate query patterns
EncryptionAWS owned or KMS keyCompliance requirements
Point-in-time recoveryEnable/disableProtection from accidental writes/deletes
TagsKey-value pairsCost tracking, resource management

Click Create table. Table status changes from Creating to Active when ready .


Using AWS Console :

  1. Navigate to Explore items
  2. Select your table
  3. Click Create item
  4. Enter attributes as JSON:
{
"Artist": "No One You Know",
"SongTitle": "Call Me Today",
"AlbumTitle": "Hey Now",
"Price": 1.98
}
  1. Click Create item

Using AWS CLI:

Terminal window
aws dynamodb put-item \
--table-name Music \
--item '{
"Artist": {"S": "No One You Know"},
"SongTitle": {"S": "Call Me Today"},
"AlbumTitle": {"S": "Hey Now"},
"Price": {"N": "1.98"}
}'

Get a single item by its primary key:

Terminal window
aws dynamodb get-item \
--table-name Music \
--key '{
"Artist": {"S": "No One You Know"},
"SongTitle": {"S": "Call Me Today"}
}'
Terminal window
aws dynamodb update-item \
--table-name Music \
--key '{
"Artist": {"S": "No One You Know"},
"SongTitle": {"S": "Call Me Today"}
}' \
--update-expression "SET Price = :p" \
--expression-attribute-values '{":p": {"N": "2.49"}}'
Terminal window
aws dynamodb delete-item \
--table-name Music \
--key '{
"Artist": {"S": "No One You Know"},
"SongTitle": {"S": "Call Me Today"}
}'

Query is the most efficient way to retrieve data. It uses primary keys to find items .

Basic query (all items with a partition key):

Terminal window
aws dynamodb query \
--table-name Music \
--key-condition-expression "Artist = :artist" \
--expression-attribute-values '{":artist": {"S": "The Acme Band"}}'

Query with sort key condition:

Terminal window
aws dynamodb query \
--table-name Music \
--key-condition-expression "Artist = :artist AND begins_with(SongTitle, :title)" \
--expression-attribute-values '{
":artist": {"S": "The Acme Band"},
":title": {"S": "S"}
}'

Scan reads every item in the table—use sparingly as it consumes more read capacity .

Terminal window
aws dynamodb scan \
--table-name Music \
--filter-expression "Genre = :genre" \
--expression-attribute-values '{":genre": {"S": "Rock"}}'
OperationPerformanceUse Case
QueryFast, efficientKnown primary key, predictable access patterns
ScanSlow, expensiveData export, infrequent analytics

DynamoDB Streams captures a time-ordered sequence of item-level modifications in a table . Stream records are stored for 24 hours.

Stream View Types :

View TypeData Included
KEYS_ONLYOnly the key attributes of modified items
NEW_IMAGEThe entire item as it appears after modification
OLD_IMAGEThe entire item as it appeared before modification
NEW_AND_OLD_IMAGESBoth before and after images

Common use cases :

  • Real-time metrics aggregation
  • Cross-region replication (Global Tables use this internally)
  • Triggering Lambda functions for event-driven architectures

DynamoDB supports ACID (Atomic, Consistent, Isolated, Durable) transactions across multiple items and tables .

OperationDescription
TransactWriteItemsAtomic, all-or-nothing write across up to 100 items
TransactGetItemsAtomic, consistent read across up to 100 items

Use cases: Financial transactions, inventory management, any operation requiring coordination across multiple items.

SQL-compatible query language for DynamoDB:

-- Select
SELECT * FROM Music WHERE Artist = 'The Acme Band'
-- Insert
INSERT INTO Music VALUE {'Artist': 'No One You Know', 'SongTitle': 'New Song'}
-- Update
UPDATE Music SET Price = 2.49 WHERE Artist = 'No One You Know' AND SongTitle = 'Call Me Today'
-- Delete
DELETE FROM Music WHERE Artist = 'The Acme Band' AND SongTitle = 'Still in Love'

DynamoDB Accelerator (DAX) is an in-memory cache that delivers microsecond latency for read-heavy workloads .

FeatureDescription
LatencyReduces read latency from milliseconds to microseconds
CompatibilityAPI-compatible with DynamoDB—no code changes required
ManagedFully managed, highly available in-memory cache
Use CaseRead-heavy, repeated access patterns
  • Applications with high read-to-write ratios
  • Repeated reads of the same items (hot keys)
  • Real-time analytics and gaming leaderboards
  • Write-heavy workloads (no benefit)
  • Applications that can’t tolerate eventual consistency
  • Small tables where native DynamoDB is already fast

DynamoDB integrates with AWS Lambda to create triggers—automated responses to data changes .

How it works:

Data Change → DynamoDB Streams → Lambda Trigger → Execute Custom Logic

Example use cases :

  • Send welcome email when new user record is created
  • Sync data to OpenSearch for full-text search
  • Update denormalized aggregates (e.g., total likes count)
  • Fan out changes to other systems via EventBridge

For advanced streaming use cases, you can capture item-level changes to Kinesis Data Streams, enabling longer retention and integration with Kinesis Data Firehose for data delivery to S3, Redshift, or OpenSearch .


11. Global Tables: Multi-Region Replication

Section titled “11. Global Tables: Multi-Region Replication”

DynamoDB Global Tables provide fully managed, multi-region, multi-master replication .

BenefitDescription
Low-latency accessUsers read/write from the closest region
High availabilityAutomatic failover across regions
Active-ActiveWrite to any region; replication is automatic
No application changesUse standard DynamoDB APIs
US-East-1 Region EU-West-1 Region
┌─────────────────┐ ┌─────────────────┐
│ DynamoDB │◄──────────│ DynamoDB │
│ Table │ Replication│ Table │
│ (Active) │──────────►│ (Active) │
└─────────────────┘ └─────────────────┘
▲ ▲
│ │
US Users EU Users

Global Tables incur additional costs for replicated writes—each write to one region is replicated to others, consuming write capacity in each region .


Backup TypeDescriptionRetention
On-demand backupManual full backupIndefinite
Point-in-time recovery (PITR)Continuous backup with second-granularity35 days

When enabled, PITR protects against accidental writes or deletes by allowing restoration to any point in time within the last 35 days, down to the second .

Enabling PITR:

Terminal window
aws dynamodb update-continuous-backups \
--table-name Music \
--point-in-time-recovery-specification PointInTimeRecoveryEnabled=True

Restoring to a point in time:

Terminal window
aws dynamodb restore-table-to-point-in-time \
--source-table-name Music \
--target-table-name Music-Backup \
--restore-date-time "2024-01-15T10:00:00Z"
Terminal window
# Create backup
aws dynamodb create-backup \
--table-name Music \
--backup-name Music-Backup-20240115
# Restore from backup
aws dynamodb restore-table-from-backup \
--target-table-name Music-Restored \
--backup-arn arn:aws:dynamodb:us-east-1:123456789012:table/Music/backup/123456

DynamoDB encrypts all data at rest by default using AWS-owned keys .

OptionDescription
AWS-owned keyDefault; no additional cost
AWS Managed KMS keyaws/dynamodb key in your account
Customer Managed KMS keyYour own key in KMS with custom policies

All DynamoDB data is encrypted in transit using TLS/SSL.

ControlDescription
IAM policiesControl which users/roles can access tables and operations
Resource-based policiesFine-grained access to specific tables
Condition keysRestrict access based on request attributes (e.g., dynamodb:LeadingKeys)
VPC EndpointsAccess DynamoDB without traversing the internet

DynamoDB is eligible for :

  • PCI DSS
  • SOC 1, 2, 3
  • HIPAA (with executed BAA)
  • FedRAMP
  • ISO 27001, 27017, 27018

ResourceFree Monthly Amount
Data storage25 GB
Read Capacity Units (RCU)25 (provisioned mode)
Write Capacity Units (WCU)25 (provisioned mode)
Stream read requests2.5 million
Global Tables replicated WCU25 (in 2 regions)
ResourcePrice
Write request units$1.25 per million
Read request units$0.25 per million
Data storage$0.25 per GB-month (25 GB free)
Continuous backups (PITR)$0.20 per GB-month
On-demand backups$0.10 per GB-month

Provisioned Capacity Pricing (us-east-1 example)

Section titled “Provisioned Capacity Pricing (us-east-1 example)”
ResourcePrice
Write Capacity Unit (WCU)$0.00065 per hour
Read Capacity Unit (RCU)$0.00013 per hour

Scenario: 10,000 users, each performing 10K reads and 5K writes per month

ComponentCalculationCost
Reads (on-demand)100M × $0.25/1M$2.50
Writes (on-demand)50M × $1.25/1M$6.25
Storage (105 GB after free tier)80 GB × $0.25$20.00
PITR backup (105 GB)105 GB × $0.20$21.00
Total (on-demand)~$50/month

Provisioned mode with reserved capacity would be significantly cheaper for steady workloads.

StrategySavings Potential
Use provisioned capacity for predictable workloads50-70% vs on-demand
Purchase reserved capacity for 1-3 yearsAdditional discount
Use DAX for read-heavy workloadsReduces RCU consumption
Right-size GSIsOnly project necessary attributes
Use S3 for large objects (>400 KB)Avoids DynamoDB storage costs
Delete unused tables and backups100% of idle costs
Set CloudWatch alarms for throttlingPrevents excessive auto-scaling

Unlike relational databases where you normalize data across many tables, DynamoDB often uses single-table design—storing multiple entity types in one table .

Example: E-commerce application

PK: "USER#123" → User record
PK: "ORDER#456" → Order record
PK: "PRODUCT#789" → Product record
PK: "USER#123#ORDERS" → User's orders collection

Why single-table design?

  • Reduces number of API calls (no JOINs across tables)
  • Lower latency (one request instead of many)
  • Simpler application logic

In DynamoDB, you design your table structure based on your access patterns, not based on data normalization .

Process:

  1. List all application access patterns
  2. Determine primary keys that satisfy each pattern
  3. Add GSIs for additional access patterns
  4. Denormalize data to avoid multiple round trips
PracticeDescription
Use meaningful partition keysHigh-cardinality attributes for even distribution
Avoid hot partitionsDon’t use timestamps as partition keys
Keep items under 400 KBStore large objects in S3, reference in DynamoDB
Use sparse indexesGSIs with partition keys only on items that need indexing
Implement exponential backoffFor retries when throttled
Use batch operationsBatchGetItem and BatchWriteItem for multiple items

CompanyUse CaseScale
DuolingoStores language lesson data31 billion items; 24,000 reads/second
Amazon retailShopping cart, session managementMillions of concurrent users
Disney+Streaming service metadataGlobal scale
Lyft, Airbnb, Capital One, NikeVarious production workloadsEnterprise scale
Use CaseWhy DynamoDB
Mobile/web backendsAuto-scaling, low latency, serverless
GamingLeaderboards, player state, session data
Ad techHigh throughput, real-time bidding
IoTDevice state, telemetry ingestion
Real-time analyticsStreams for real-time processing
Shopping cartsHigh write throughput, eventual consistency acceptable

17. Limitations and When NOT to Use DynamoDB

Section titled “17. Limitations and When NOT to Use DynamoDB”
LimitationValueImpact
Maximum item size400 KBCan’t store large documents
Maximum GSI per table20 (default)Limited query flexibility
Maximum LSI per table5Must be created at table creation
Stream retention24 hoursLimited replay window
No JOIN operationsN/AMust denormalize or make multiple requests
ScenarioBetter Alternative
Complex queries with JOINsAmazon RDS or Aurora
Ad-hoc analytics and BIRedshift or Athena
Large binary objects (>400 KB)S3 (store reference in DynamoDB)
Full SQL query capabilitiesRDS/Aurora with SQL
Graph data with complex relationshipsAmazon Neptune
Avoiding vendor lock-inMongoDB Atlas or Cassandra

This glossary includes key terms directly related to Amazon DynamoDB.


ACID Transactions Atomic, Consistent, Isolated, Durable transactions that enable coordinated, all-or-nothing changes to multiple items across one or more tables .

Attribute A fundamental data element within an item; a key-value pair. Attributes are similar to fields or columns in other database systems .


BatchGetItem Operation that retrieves up to 100 items from one or more tables in a single API call.

BatchWriteItem Operation that puts or deletes up to 25 items across one or more tables in a single API call.


Capacity Unit Unit of measure for read and write throughput. Read capacity units (RCU) and write capacity units (WCU) determine the throughput you can consume .

Composite Primary Key Primary key consisting of two attributes: a partition key and a sort key. Enables flexible querying with range conditions .

Conditional Write Write operation that succeeds only if a specified condition evaluates to true. Used for optimistic concurrency control.


DAX (DynamoDB Accelerator) In-memory cache that delivers microsecond latency for read-heavy workloads. API-compatible with DynamoDB .

Document Type Data type that supports nested attributes, including maps and lists. Enables rich, hierarchical data structures.

DynamoDB Streams Time-ordered sequence of item-level modifications in a table. Stream records persist for 24 hours .


Eventually Consistent Read Read operation that may not reflect recent writes. Default consistency mode; consumes half the read capacity of strongly consistent reads .

Expression Attribute Values Placeholders in DynamoDB expressions to prevent injection attacks and handle type safety.

Expression Attribute Names Placeholders for attribute names that conflict with DynamoDB reserved words.


Global Secondary Index (GSI) Index with partition and sort keys that can be different from the base table. Quota of 20 per table. Allows querying on alternate attributes .

Global Table Multi-region, multi-master replication feature. Provides low-latency local access for globally distributed applications .


Hash Attribute Alternative name for partition key. Derives from internal hash function that determines storage partition .

Hot Partition Partition that receives a disproportionate number of requests, causing throttling. Avoid by choosing high-cardinality partition keys.


Item A group of attributes uniquely identifiable by a primary key. Items are similar to rows or records in other databases. No limit on number of items per table .

Item Collection Group of items in a table that share the same partition key.


Kinesis Data Streams for DynamoDB Feature that captures item-level changes to a Kinesis data stream, enabling longer retention and advanced streaming applications .


Local Secondary Index (LSI) Index with the same partition key as the base table but a different sort key. Must be created when the table is created. Quota of 5 per table .


Map Document data type that contains nested attributes. Maps can contain other maps or lists up to 32 levels deep .

Multi-AZ Replication Automatic replication of data across multiple Availability Zones within a region for high availability and durability.


Nested Attribute Attribute that contains other attributes (map) or a list of values. DynamoDB supports nesting up to 32 levels deep .

NoSQL Workbench Visual tool for designing, creating, and querying DynamoDB tables. Supports data modeling and visualization .


On-Demand Capacity Mode Capacity mode where DynamoDB scales automatically based on workload. Pay per request. Best for unpredictable workloads .


PartiQL SQL-compatible query language for DynamoDB. Supports SELECT, INSERT, UPDATE, DELETE statements.

Partition Physical storage unit internal to DynamoDB. Data is distributed across partitions based on partition key hash values.

Partition Key Primary key composed of a single attribute. DynamoDB hashes the partition key to determine storage partition .

Point-in-Time Recovery (PITR) Continuous backup feature that enables restoration to any second within the last 35 days .

Projection The set of attributes copied from the base table to a secondary index. Minimizing projection reduces storage costs .

Provisioned Capacity Mode Capacity mode where you specify read and write capacity units. Supports auto-scaling. Best for predictable workloads .

Provisioned Throughput Maximum read and write capacity that a table or index can consume. Configured in RCU and WCU units.


Query Operation that retrieves items using primary key values. Most efficient read operation in DynamoDB .


Range Attribute Alternative name for sort key. Derives from ability to query ranges of values .

Read Capacity Unit (RCU) One strongly consistent read per second for an item up to 4 KB. One eventually consistent read consumes 0.5 RCU .

Reserved Capacity Discounted capacity purchased for 1-3 year commitments. Provides significant savings over on-demand provisioned pricing .


Scalar Attribute Attribute that holds a single value. Types include string, number, binary, Boolean, and null .

Scan Operation that reads every item in a table. Inefficient for large tables; prefer Query when possible .

Schemaless Property of DynamoDB where items in the same table can have different attributes. No need to define schema beforehand .

Secondary Index Index that allows querying using an alternate key. Supports global secondary indexes (GSIs) and local secondary indexes (LSIs) .

Simple Primary Key Primary key consisting of only a partition key. No two items can share the same partition key value .

Sort Key Second attribute in a composite primary key. Items with the same partition key are stored sorted by sort key .

Sparse Index Index where only items with a specific attribute are indexed. Efficient for querying subsets of data.

Strongly Consistent Read Read that returns the most recent write. Consumes full read capacity (1 RCU per 4 KB) .


Table Collection of data items. DynamoDB stores data in tables, similar to relational databases .

Time to Live (TTL) Feature that automatically deletes items after a specified timestamp. Used for session data, temporary records.

Transaction See ACID Transactions.


Write Capacity Unit (WCU) One write per second for an item up to 1 KB. Larger items consume multiple WCUs .


Amazon DynamoDB is a powerful, fully managed NoSQL database designed for applications that require consistent single-digit millisecond latency at any scale. Its serverless nature, automatic scaling, and flexible data model make it an excellent choice for modern cloud-native applications.

Key Takeaways:

  • Core components: Tables → Items → Attributes
  • Primary keys: Partition key only or partition key + sort key
  • Capacity modes: On-demand (pay per request) or Provisioned (pay per capacity unit)
  • Indexes: GSIs (different keys) and LSIs (same partition key)
  • Advanced features: DAX (microsecond caching), Streams (change capture), Global Tables (multi-region)
  • Security: Encryption at rest by default, VPC endpoints, IAM fine-grained access
  • Limitations: 400 KB item size, no JOINs, vendor lock-in

Getting Started Recommendations:

  • Start with the DynamoDB console tutorial (10 minutes, free tier eligible)
  • Use on-demand mode for development and unpredictable workloads
  • Design based on access patterns, not normalization
  • Enable PITR for production tables
  • Use DAX for read-heavy, latency-sensitive applications
  • Monitor with CloudWatch metrics (ThrottledRequests, SystemErrors)