DynamoDB Data Modeling
System Design · Scaling & Data · Advanced · 22 min
Design DynamoDB partition and sort keys from your access patterns, use single-table design and GSIs, and avoid hot partitions.
A giant library with many rooms. The partition key decides which room a book goes into; the sort key decides its place on that room's shelf. Ask for 'room 7, shelf section ORDER#' and you walk straight there.
The idea in everyday words
Think of a post office with hundreds of sorting bins. The partition key is the postcode: it decides which bin a letter lands in, and each bin's clerk can only handle so many letters a minute. The sort key is the house number, so letters inside a bin stay in order. If every letter in the city had the same postcode, one clerk would drown while the rest sat idle.
Partition key, sort key and item collections
A DynamoDB table holds items (rows, stored as JSON-like maps). Every item has a primary key:
- Partition key (pk): DynamoDB hashes it to choose a partition, a slice of storage and throughput on some servers. Exact match only.
- Sort key (sk), optional: orders items inside one partition key. You can ask for ranges:
begins_with,between,<,>.
All items with the same pk form an item collection: grouped by pk and kept sorted by sk, so one Query reads them in order. (A very large collection can span several partitions behind the scenes, unless the table has an LSI, see below.)
| Operation | What you give | Cost |
|---|---|---|
| GetItem | full pk (+ sk) | one item, cheapest |
| Query | exact pk + optional sk condition | reads only that collection, in sk order |
| Scan | nothing | reads the WHOLE table, avoid on hot paths |
Tiny example: pk = USER#1, sk = ORDER#2024-03. "All orders of user 1" = Query pk = USER#1 AND begins_with(sk, "ORDER#"). Add ScanIndexForward=False to get newest first.
Sort keys sort as strings (by bytes). "ORDER#10" comes before "ORDER#9". Use ISO dates (2024-03-07) or zero-padded numbers (000042) so string order equals real order.
List your access patterns first
With SQL you model the data first and write any query later. DynamoDB flips it: list every question the app will ask, then design keys so each question is one GetItem or Query. There are no joins to save you later.
Example shop, access patterns → keys:
| # | Access pattern | Key design |
|---|---|---|
| 1 | Get a user's profile | pk = USER#id, sk = PROFILE |
| 2 | List a user's orders, newest first | pk = USER#id, sk begins_with ORDER#, descending |
| 3 | Get one order by order id | GSI1: pk = ORDER#id |
| 4 | Orders waiting to ship, oldest first | GSI2: pk = STATUS#PENDING, sk = created_at (sparse) |
Single-table design puts several entity types (users, orders, addresses) in ONE table with generic attribute names like pk and sk. Related items share a pk, so one Query returns the user and their recent orders together, the "join" is done at write time.
The trade-off: single-table design is fast and cheap per request, but harder to read, and adding a brand-new access pattern later may need a new index or a backfill. Many teams happily use one table per entity when their patterns are simple. Both are valid; say why you chose.
Secondary indexes: GSI and LSI
An index is a second copy of (some of) your data, keyed differently, kept up to date by DynamoDB.
| Global secondary index (GSI) | Local secondary index (LSI) | |
|---|---|---|
| Keys | any new pk and sk | same pk, different sk |
| When created | any time | only when the table is created |
| Consistency | eventually consistent reads only | strongly consistent reads allowed |
| Capacity | its own throughput | shares the table's |
| Size limit | none per pk | 10 GB per item collection (all items with one pk, plus their LSI entries) |
Sparse index trick: an item only appears in a GSI if it has the GSI's key attribute. Give gsi2pk = STATUS#PENDING only to pending orders, then remove it when they ship. The index holds just the work queue.
Overloading: name GSI keys generically (gsi1pk, gsi1sk) so different entity types can reuse one index for different patterns.
Watch out: a GSI with a low-cardinality pk (like STATUS#PENDING for every order) can itself become hot. Writes to the table are throttled if a GSI cannot keep up.
The LSI catch (a classic follow-up): with an LSI, one partition key's item collection cannot grow past 10 GB, and writes for that pk start failing (ItemCollectionSizeLimitExceededException). You also cannot add an LSI later. So the default advice is: prefer GSIs, and use an LSI only when you truly need strongly consistent reads on an alternate sort order and each pk stays small.
Hot partitions, capacity modes and conditional writes
Hot partition = one partition key gets far more traffic than the rest. Each partition has a fixed throughput ceiling (see the DynamoDB docs), so a hot key gets throttled even if the table as a whole has plenty of spare capacity. Adaptive capacity shifts throughput toward busy partitions and DynamoDB can split partitions, but traffic to a single key value still has a ceiling.
Fixes: choose a high-cardinality pk (user id, order id, device id), and for a truly hot logical key use write sharding: DAY#2024-03-07# + (n % 4), then read all 4 shards and merge.
Capacity modes:
- On-demand: pay per request, no planning, absorbs spiky or unknown traffic. Great default for new apps.
- Provisioned (+ auto scaling): you set read/write capacity units. Cheaper for steady, predictable load. Check the AWS pricing page for the break-even.
Conditional writes make DynamoDB check a condition atomically before writing: no read-then-write race.
# Create only if new (idempotent sign-up)
table.put_item(Item={"pk": "USER#ana", "sk": "PROFILE"},
ConditionExpression="attribute_not_exists(pk)")
# Optimistic locking: update only if nobody changed it since we read v=3
table.update_item(Key={"pk": "ORDER#9", "sk": "META"},
UpdateExpression="SET #s = :new, v = :v4",
ConditionExpression="v = :v3",
ExpressionAttributeNames={"#s": "status"},
ExpressionAttributeValues={":new": "SHIPPED", ":v3": 3, ":v4": 4})
A failed condition raises ConditionalCheckFailedException. Need several items to change together? TransactWriteItems (all or nothing, limited number of items).
Other clouds: GCP Bigtable / Firestore, Azure Cosmos DB (partition key + RU capacity); open source Cassandra / ScyllaDB use the same partition-key-plus-clustering-key idea.
Go deeper (senior / staff)
Failure modes you should name.
- GSI back-pressure: if a GSI is under-provisioned or has a hot key, DynamoDB throttles writes to the base table. One careless index can take down the write path.
- Transaction contention: TransactWriteItems on popular items fails with
TransactionCanceledExceptionwhen two transactions touch the same item. Keep transactions small and retry with jittered backoff. - Scan in a hot path reads (and bills) every item. Use Export to S3 plus Athena for analytics instead.
Multi-region with global tables. Global tables replicate every Region's writes to the others. In the default mode replication is asynchronous and conflicts resolve by last writer wins, and a conditional write is only checked in the Region that received it. So two Regions can both "create username ana if not exists" and one sign-up silently disappears. Fixes: route each item's writes to a home Region (for example by user), or use the newer multi-Region strong consistency mode where it fits (check the docs for supported Regions and its latency cost: every write waits for another Region).
Cost reasoning without numbers.
- Every GSI write is another write you pay for. Project only the attributes the pattern needs (KEYS_ONLY or INCLUDE), not ALL.
- Read and write units are charged per size step, so big items cost more on every touch. Keep large blobs in S3 and store the key.
- TTL deletes do not consume write capacity, so expire sessions and stale data with TTL and archive via Streams if you must keep it.
- Steady load is usually cheaper on provisioned with auto scaling than on-demand; check the AWS pricing page for the break-even.
Trade-off to say out loud: single-table design optimises the known patterns; a new one means a new GSI or a migration.
Step by step
- List patterns:
- profile by user, 2) user's orders newest first, 3) order by id. Three questions, written down before any table exists.
- Pick the base keys:
pk = USER#1, sk = PROFILE for the profile; pk = USER#1, sk = ORDER#2024-03 for each order. Patterns 1 and 2 now hit one item collection.
- Query pattern 2:
Query pk = USER#1, begins_with(sk, 'ORDER#'), ScanIndexForward = False → ORDER#2024-03, ORDER#2024-02, ORDER#2024-01. PROFILE is skipped by the prefix.
- Pattern 3 needs a GSI:
We only know the order id, not the user. Add gsi1pk = ORDER#77 on each order item; Query the GSI with pk = ORDER#77.
- Check the heat:
pk = USER#id spreads writes across many partitions. A pk of DAY#2024-03-07 would send every order today to one partition: hot, throttled.
- Guard the writes:
Create profiles with ConditionExpression attribute_not_exists(pk), so a retried sign-up cannot overwrite an existing user.
Code example
# A toy single-table DynamoDB: item collections sorted by sort key.
table = {} # pk -> {sk: item}
def put_item(item, if_not_exists=False):
coll = table.setdefault(item["pk"], {})
if if_not_exists and item["sk"] in coll:
return "ConditionalCheckFailedException"
coll[item["sk"]] = item
return "OK"
def query(pk, prefix="", forward=True):
coll = table.get(pk, {})
keys = sorted(k for k in coll if k.startswith(prefix))
if not forward:
keys.reverse()
return [coll[k] for k in keys]
print(put_item({"pk": "USER#1", "sk": "PROFILE", "name": "Ana"}, if_not_exists=True))
print(put_item({"pk": "USER#1", "sk": "PROFILE", "name": "Eve"}, if_not_exists=True))
for month in ["2024-03", "2024-01", "2024-02"]:
put_item({"pk": "USER#1", "sk": "ORDER#" + month, "total": 10})
print([i["sk"] for i in query("USER#1", "ORDER#", forward=False)])
print(query("USER#1", "PROFILE")[0]["name"])
# A GSI is just another index keyed differently: order id -> owner
gsi1 = {"ORDER#2024-02": "USER#1"}
print("owner of ORDER#2024-02:", gsi1["ORDER#2024-02"])Complexity
- Time: O(n log n): filter n items, then sort the k matches. Real DynamoDB reads only the one partition, already sorted.
- Space: O(k) for the k matching items returned.
Interview tips
Open with: 'Let me list the access patterns first', then design pk/sk per pattern. Interviewers look for exactly this habit.
Explain hot partitions with a concrete bad key (today's date) and a fix (high-cardinality key or write sharding).
Know GSI vs LSI: GSI any time, eventually consistent, own capacity; LSI at table creation, same pk, can be strongly consistent.
On-demand for unknown or spiky load, provisioned with auto scaling for steady load. Mention checking the pricing page rather than quoting numbers.
Use conditional writes for idempotency and optimistic locking; TransactWriteItems for all-or-nothing changes across items.
Challenge: Simulate a DynamoDB Query
Write query_items(items, pk, sk_prefix, forward).
itemsis a list of dicts, each with stringpkandsk(plus any other fields).- Keep items whose
pkequalspkand whoseskstarts withsk_prefix(an empty prefix matches everything; matching is case-sensitive). - Return them sorted by
skas strings, ascending ifforwardis true, descending if false (likeScanIndexForward). - Return the whole item dicts unchanged.
Example: with orders ORDER#2024-03 and ORDER#2024-01 and a PROFILE item under "USER#1", query_items(items, "USER#1", "ORDER#", True) → the 2024-01 order, then the 2024-03 order.
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- DynamoDB: designing partition keys
- DynamoDB: global secondary indexes
- Time Based Key-Value Store (sorted keys + lookup) (Medium)
More in Scaling & Data
- Scaling & Load Balancers
- Caching (Redis & CDN)
- Databases: SQL, NoSQL, Sharding
- Choosing a Database on AWS
- Consistent Hashing
Previous: Choosing a Database on AWS · Next: Consistent Hashing