DynamoDB
Amazon DynamoDB in depth — tables, items and primary keys, partition and sort keys, how partitioning works, queries vs scans, global and local secondary indexes, single-table design and access patterns, consistency, capacity modes, conditional writes, transactions, streams, TTL, global tables, DAX and the limits that shape data models.
DynamoDB is a fully managed, serverless key-value and document database that delivers single-digit-millisecond latency at any scale — Amazon's own retail systems push it to millions of requests per second. There are no servers, no connections to pool and no maintenance windows. The price of that scalability is a different way of modelling data: you design around access patterns, not entities (NoSQL databases).
Core concepts
Table: Orders
┌──────────────────┬─────────────────────┬──────────┬────────┬───────────┐
│ PK (partition) │ SK (sort) │ status │ total │ … │
├──────────────────┼─────────────────────┼──────────┼────────┼───────────┤
│ CUSTOMER#42 │ PROFILE │ │ │ name, … │
│ CUSTOMER#42 │ ORDER#2026-11-30#981│ SHIPPED │ 1499 │ │
│ CUSTOMER#42 │ ORDER#2026-12-03#1043│ PLACED │ 820 │ │
│ CUSTOMER#77 │ PROFILE │ │ │ name, … │
└──────────────────┴─────────────────────┴──────────┴────────┴───────────┘- Items (rows) are schemaless apart from the key; each item can be up to 400 KB.
- The primary key is either a partition key alone, or a partition key + sort key (composite).
- All items with the same partition key form an item collection, stored together and sorted by the sort key.
How partitioning works
DynamoDB hashes the partition key to pick a physical partition (storage plus compute). Each partition serves up to about 3,000 read units and 1,000 write units per second and ~10 GB; DynamoDB splits partitions as data and traffic grow (Sharding and partitioning, Consistent hashing).
So the cardinal rule: choose a high-cardinality partition key that spreads traffic evenly. A key like status = "PENDING" or today's date sends all traffic to one partition — a hot partition that throttles while the rest sit idle. Adaptive capacity helps by shifting throughput to busy partitions, but can't beat the per-partition ceiling. For extreme hot keys, write-shard them (DATE#2026-12-04#7, with a random suffix 0–9) and fan reads out.
Reading data
| Operation | What it does | Cost |
|---|---|---|
| GetItem | One item by full primary key | Cheapest, fastest |
| Query | Items in one partition, optionally filtered by a sort-key condition (begins_with, between, >), in sort order | Proportional to items read |
| BatchGetItem | Up to 100 items by key in parallel | Sum of gets |
| Scan | Reads the entire table | Expensive — avoid in request paths |
Filter expressions are applied after reading, so they reduce what's returned but not what's consumed. Design keys so queries read only what they need.
from boto3.dynamodb.conditions import Key
orders = table.query(
KeyConditionExpression=Key("PK").eq("CUSTOMER#42") & Key("SK").begins_with("ORDER#2026-12"),
ScanIndexForward=False, # newest first
Limit=20,
)["Items"]const { Items } = await db.send(new QueryCommand({
TableName: "Orders",
KeyConditionExpression: "PK = :pk AND begins_with(SK, :prefix)",
ExpressionAttributeValues: { ":pk": "CUSTOMER#42", ":prefix": "ORDER#2026-12" },
ScanIndexForward: false,
Limit: 20,
}));QueryResponse res = ddb.query(q -> q.tableName("Orders")
.keyConditionExpression("PK = :pk AND begins_with(SK, :prefix)")
.expressionAttributeValues(Map.of(
":pk", AttributeValue.fromS("CUSTOMER#42"),
":prefix", AttributeValue.fromS("ORDER#2026-12")))
.scanIndexForward(false).limit(20));Results are paginated (1 MB per page); follow LastEvaluatedKey.
Secondary indexes
When you need to query by a different attribute, add an index:
| Global secondary index (GSI) | Local secondary index (LSI) | |
|---|---|---|
| Key | Any partition key + optional sort key | Same partition key, different sort key |
| Created | Any time | Only at table creation |
| Consistency | Eventually consistent only | Strong or eventual |
| Capacity | Its own | Shares the table's |
| Limit | 20 per table (default) | 5 per table; caps item collections at 10 GB |
GSIs are sparse: only items that have the index key attributes appear in the index — a neat way to index "only orders that are still open". Project only the attributes you need to keep indexes small.
Data modelling: access patterns first
- List every access pattern the application needs: "get customer profile", "list a customer's orders newest first", "get order by ID", "list open orders by warehouse".
- Design primary keys and GSIs so each pattern is a GetItem or a single Query.
- Pre-join related data: put items that are read together in the same partition with prefixed sort keys (
PROFILE,ORDER#…), so one query returns a customer and their recent orders. - Denormalise where needed and accept duplicated data — storage is cheap, joins don't exist.
- Use overloaded generic keys (
PK,SK,GSI1PK,GSI1SK) so many entity types can share one table — single-table design.
| Access pattern | Key design |
|---|---|
| Customer profile | PK = CUSTOMER#42, SK = PROFILE |
| Customer's orders by date | PK = CUSTOMER#42, SK begins_with ORDER# |
| Order by ID | GSI1: GSI1PK = ORDER#1043, GSI1SK = ORDER#1043 |
| Open orders by warehouse | Sparse GSI2: GSI2PK = WAREHOUSE#BLR, GSI2SK = PLACED#2026-12-03 (only set while open) |
Single-table design minimises round trips but is harder to read and evolve; many teams use a table per bounded context with a few GSIs as a pragmatic middle ground. Either way, if your access patterns are unknown or you need ad-hoc queries and joins, a relational database is the better tool (RDS and Aurora).
Consistency, capacity and writes
- Reads are eventually consistent by default (usually consistent within a second); request strongly consistent reads at twice the read-unit cost (not available on GSIs or across regions in global tables).
- Capacity modes: On-demand — pay per request, scales instantly, the default choice — or provisioned read/write capacity units with auto scaling, cheaper for steady predictable load. One RCU = one strongly consistent 4 KB read per second; one WCU = one 1 KB write per second.
- Conditional writes make updates safe without locks:
table.put_item(
Item={"PK": "ORDER#1043", "SK": "ORDER#1043", "status": "PLACED"},
ConditionExpression="attribute_not_exists(PK)", # idempotent create
)
table.update_item(
Key={"PK": "PRODUCT#7", "SK": "STOCK"},
UpdateExpression="SET qty = qty - :n, version = version + :one",
ConditionExpression="qty >= :n AND version = :v", # optimistic locking
ExpressionAttributeValues={":n": 1, ":one": 1, ":v": 12},
)- Transactions:
TransactWriteItems/TransactGetItemsgive ACID across up to 100 items (in one region), at twice the capacity cost (Transactions).
Streams, TTL and global tables
- DynamoDB Streams: an ordered change log of item-level modifications (per partition key), retained 24 hours. Trigger Lambda to update search indexes, aggregate counters, send notifications, or implement the outbox pattern (Distributed transactions).
- TTL: set an epoch-seconds attribute and DynamoDB deletes expired items for free (typically within a few days) — sessions, temporary tokens, old events.
- Global tables: multi-region, multi-active replication. Concurrent writes to the same item in different regions resolve as last writer wins by default, with an option for multi-region strong consistency.
- Point-in-time recovery (up to 35 days) and on-demand backups; export to S3 for analytics.
- DAX: an in-memory, write-through cache in front of DynamoDB for microsecond reads.
QWhat makes a good DynamoDB partition key?medium
High cardinality and evenly distributed access, so requests spread across many partitions — a user ID, order ID or device ID rather than a status, a date or a small set of categories. It should also match how the application looks data up, so most requests are GetItem or a Query on one partition. If a key is inherently hot, such as today's date for an event log, add a random or computed suffix to spread writes and query the shards in parallel.
QWhen would you choose DynamoDB over a relational database?medium
When access patterns are well known and key-based, you need predictable low latency at very high or very spiky scale, you want zero operational overhead and pay-per-request pricing, and the data model doesn't need ad-hoc queries, complex joins or large multi-row transactions — for example sessions, shopping carts, user profiles, IoT data, leaderboards and metadata stores. If requirements are evolving, need flexible querying, reporting or rich relational integrity, a relational database is usually the better fit.
QWhat's the difference between a Query and a Scan, and why do filter expressions not save capacity?easy
A Query reads items from a single partition key, optionally narrowed by a sort-key condition, so it only touches the relevant items. A Scan reads every item in the table or index. Filter expressions are applied after items are read from storage, so capacity is consumed for everything read even if most of it is filtered out — the fix is a better key or an index, not a filter.
- DynamoDB is serverless key-value storage with single-digit-millisecond latency at any scale.
- Items are located by partition key (hashed to a partition) and ordered by sort key within it; choose high-cardinality keys to avoid hot partitions.
- Prefer GetItem and Query; avoid Scans and remember filters don't reduce consumed capacity.
- GSIs add alternative access patterns (eventually consistent, can be sparse); LSIs must be created with the table.
- Model from access patterns: pre-join related items in item collections, denormalise, and consider single-table design.
- Use on-demand capacity by default, conditional writes for idempotency and optimistic locking, transactions sparingly, and Streams for change-driven processing.