Lesson 19 of 30Modern AWS
DynamoDB Data Modeling
Design DynamoDB tables from access patterns: composite keys, GSIs, sparse indexes, hot partitions, conditional writes, transactions and streams.
Your team picked DynamoDB for the new order service because it scales without anyone babysitting it. Six months later, product asks for "all open orders in the London warehouse, oldest first", and the only way to answer is a Scan that reads every item in the table, slowly and expensively. Nobody made a mistake in the code. The mistake was in the keys, which were designed around the entities instead of around the questions the app asks. This lesson teaches the method that avoids that: list the access patterns first, then shape keys and indexes so every pattern is one cheap Query or GetItem.
You met the basics in Databases on AWS. Here you go deep enough to design a table in a review and defend it.
Start from access patterns, not entities
In Postgres you normalize first and write queries later, because the planner can join anything. DynamoDB has no joins and no planner. It does two things efficiently: fetch one item by its full key, and fetch a sorted range of items sharing a partition key, on the table or on an index. So the design question is "what questions will the app ask, and how often?"
The method seniors use:
- List the entities and how they relate: customers, orders, order lines, products, warehouses.
- List every access pattern with its parameters and a rough frequency. Include writes, and include the boring ones.
- Design keys so each pattern maps to one call. Work from the most frequent pattern down.
- Write the access-pattern table as the deliverable. It is what you review with the team and what the next engineer reads.
For a small shop, the table looks like this:
| # | Access pattern | Frequency | How it is served |
|---|---|---|---|
| 1 | Get product by id | Very high | GetItem PK=PRODUCT#p1, SK=META |
| 2 | Get an order with its lines | High | Query PK=ORDER#o1 |
| 3 | Customer page: profile plus newest orders | High | Query GSI1 PK=CUST#c1, descending |
| 4 | A customer's orders in a date range | Medium | Query GSI1 PK=CUST#c1, SK BETWEEN two dates |
| 5 | Which orders contain product p1 (recalls) | Low | Query GSI1 PK=PRODUCT#p1 |
| 6 | Open orders for a warehouse, oldest first | Medium | Query GSI2 PK=WH#lon (sparse) |
| 7 | Sign up with an email that must be unique | Low | TransactWriteItems with attribute_not_exists |
| 8 | Change an order's status without lost updates | Medium | UpdateItem with a version condition |
If a pattern has no row in that last column, you do not have a design yet. And if you cannot list the patterns at all, because the product is young and the questions keep changing, that is a strong signal to use Postgres instead. More on that at the end.
Key design: item collections and composite sort keys
An item collection is every item that shares a partition key. It is the closest thing DynamoDB has to a join: you store related items together on purpose so one Query returns them all, sorted by sort key.
The keys in the design above are generic attribute names (PK, SK, GSI1PK, GSI1SK) holding prefixed values. Generic names let one table and one index hold many entity types, which is the core trick of single-table design.
| PK | SK | GSI1PK | GSI1SK | other |
|---|---|---|---|---|
CUST#c1 | PROFILE | CUST#c1 | PROFILE | name, email |
ORDER#o1 | #META | CUST#c1 | ORDER#2026-09-30#o1 | status, total, version |
ORDER#o1 | ITEM#p1 | PRODUCT#p1 | ORDER#2026-09-30#o1 | qty, price |
ORDER#o1 | ITEM#p2 | PRODUCT#p2 | ORDER#2026-09-30#o1 | qty, price |
EMAIL#ada@example.com | EMAIL | owner: c1 |
Things to notice:
- Composite sort keys like
ORDER#2026-09-30#o1encode a hierarchy. ISO dates sort correctly as strings, sobegins_with(SK, "ORDER#2026-10")means "October" andBETWEENgives any range. The trailing id keeps keys unique when two orders share a date. - Sort order is a design tool.
#METAsorts beforeITEM#...because#comes before letters in byte order, so the order header always comes back first. On GSI1,PROFILEsorts afterORDER#..., so a descending query returns the profile and then the newest orders: one call renders the whole customer page. - Hierarchical keys such as
UK#London#STORE#12answer "all UK stores", "all London stores" and "store 12" with prefix queries. - Many-to-many with an adjacency list. An order has many products and a product is in many orders. Each order line is an edge. It lives in the order's collection on the base table (pattern 2), and the index flips it so it also lives in the product's collection (pattern 5). That flipped index is often called an inverted index.
Run the design. This is a small in-memory model of a table with two GSIs. It honors the rules that matter: items only appear in an index if they have that index's key attributes, sort keys sort as strings, and conditions are checked before writes.
Press Run (⌘ Enter) to see what happens.Try adding a ninth access pattern, such as "all orders placed on a given day across all customers", and see which index (if any) can serve it. That exercise is the whole job.
GSIs and LSIs
A global secondary index (GSI) is a second copy of selected items, keyed differently, that DynamoDB maintains for you. What you need to know about it:
- It is eventually consistent. Writes to the base table propagate to the GSI asynchronously, usually within a fraction of a second, and you cannot ask for a strongly consistent read on a GSI. Read-your-own-write flows (create an order, then immediately list the customer's orders) must either read the base table or tolerate a short lag.
- It has its own throughput. In provisioned mode you set capacity per GSI. If a GSI cannot keep up with writes, DynamoDB throttles writes to the base table too. An under-provisioned index can take down your write path.
- Projections decide which attributes are copied:
KEYS_ONLY,INCLUDEa list, orALL. Smaller is cheaper to write, but a missing attribute costs a second fetch from the base table. - Sparse indexes. An item only appears in an index if it has the index's key attributes. Pattern 6 uses this: an order gets
GSI2PKwhile it is pending and loses it when it ships, so the index only ever holds open orders. It stays small no matter how many historic orders you keep. - Overloading. GSI1 serves both "orders by customer" and "orders by product" because different item types put different values in
GSI1PK. One index, several patterns. - Limits. The default quota is 20 GSIs per table, and you can add one to a live table (DynamoDB backfills it).
- Multi-attribute keys. Since late 2025, a GSI key can combine several existing attributes (up to four each for partition and sort key), which removes much of the string concatenation for new indexes. Existing code is full of the concatenated style, so you must still read it fluently.
A local secondary index (LSI) keeps the same partition key and offers a different sort key. It differs from a GSI in ways that make it a rare choice:
- It must be defined when you create the table. You cannot add one later.
- It shares the base table's throughput and supports strongly consistent reads.
- A table with any LSI is limited to 10 GB per item collection (all items with one partition key value, plus their LSI entries). A busy customer or tenant that grows past that cannot accept more writes.
- At most 5 per table.
Default to GSIs. Reach for an LSI only when you truly need a strongly consistent alternate sort order and you know every item collection stays small.
The write goes to the base table. Any condition is evaluated here, atomically, against the current item. If it fails, nothing is written anywhere.
Query, Scan and the Limit trap
Query reads one item collection, optionally narrowed by a sort key condition. Scan reads everything. A Scan in a request path is a bug waiting for the table to grow; keep Scans for one-off backfills, and use the export-to-S3 feature for bulk exports.
The details that bite in production:
- Pages are 1 MB. A Query or Scan returns at most 1 MB of data per call (measured before any filter). If there is more, the response has
LastEvaluatedKey; pass it back asExclusiveStartKeyto get the next page. Your API should expose an opaque cursor built from it, not page numbers. FilterExpressionruns after the read. You pay for every item read, including the ones the filter throws away. A filter is for trimming a small result, never a substitute for a key condition.Limitis applied before the filter.Limit=20means "read 20 items", not "return 20 matches". With a filter, you can get 3 items back, or zero, plus aLastEvaluatedKey. Code that stops when it gets an empty page misses data.- Items are capped at 400 KB, attribute names included. Blobs go in S3 with a pointer; growing lists (comments on a post) become separate items in a collection.
- Strongly consistent reads cost twice the read capacity of eventually consistent reads, and only exist on the base table and LSIs.
What does this print?
orders = [{"sk": f"ORDER#{i}", "status": "SHIPPED" if i % 3 else "PENDING"}
for i in range(1, 11)]
page = orders[:5] # Query with Limit=5
matches = [o for o in page if o["status"] == "PENDING"] # FilterExpression
print(len(matches))Hot partitions and how to spread load
DynamoDB stores data in partitions and routes each item by a hash of its partition key. Each partition can serve about 3,000 read units and 1,000 write units per second. Table-level capacity does not help if all your traffic lands on one key: a table rated for 40,000 writes per second still throttles if every write targets PK = "2026-10-20".
Two features soften this, and you should know their limits:
- Adaptive capacity shifts throughput toward busy partitions automatically, and DynamoDB can split a partition that stays hot so its keys spread across more partitions. This rescues uneven but spread-out traffic.
- It cannot help a single hot item (one counter everyone increments), it cannot split an item collection locked together by an LSI, and splitting by sort key range does not help when every write goes to the newest sort key, such as a timestamp. A very hot key is still your problem.
The fixes, in order of preference:
- Choose high-cardinality partition keys: user id, order id, device id. Most hot partitions are design mistakes like using a date, a status or a tenant id that one huge tenant dominates.
- Write sharding when a single logical key genuinely gets heavy writes (a global counter, a leaderboard for one event). Append a suffix:
VOTES#2026-10-20#0to#9. Writes pick a suffix at random or by hashing an id, which spreads them over ten keys. Reads must query all ten and merge, so only shard the keys that need it. - Cache hot reads in front of the table (DAX or ElastiCache) when one item is read thousands of times per second.
Correctness: conditions, versions and transactions
DynamoDB gives you atomic single-item operations with conditions, and that covers most correctness needs.
Uniqueness with attribute_not_exists. There are no unique constraints on non-key attributes. To make emails unique, store a second item whose key is the email, and write it with a condition:
import boto3
client = boto3.client("dynamodb")
client.transact_write_items(
TransactItems=[
{"Put": {
"TableName": "shop",
"Item": {"PK": {"S": "CUST#c3"}, "SK": {"S": "PROFILE"},
"email": {"S": "eve@example.com"}},
"ConditionExpression": "attribute_not_exists(PK)",
}},
{"Put": {
"TableName": "shop",
"Item": {"PK": {"S": "EMAIL#eve@example.com"}, "SK": {"S": "EMAIL"},
"owner": {"S": "c3"}},
"ConditionExpression": "attribute_not_exists(PK)",
}},
],
ClientRequestToken="signup-7f3a9c", # makes a retried call idempotent
)If the email item exists, the whole transaction is cancelled with TransactionCanceledException, and the cancellation reasons say which condition failed.
Optimistic locking with a version attribute. Two workers read order o1 at version 3. Both try to update it. Each writes with ConditionExpression: "version = :seen" and SET version = version + 1. The first wins; the second gets ConditionalCheckFailedException, re-reads, and decides again. No locks, no lost updates. (The ship function in the simulator does exactly this.)
Transactions. TransactWriteItems and TransactGetItems give all-or-nothing across up to 100 items (and 4 MB) in one Region, even across tables. The costs:
- Each item in a transaction consumes twice the capacity of a normal write or read, because DynamoDB runs a prepare and a commit.
- Two actions in one transaction cannot touch the same item.
- Transactions conflict with concurrent writes to the same items and can be cancelled; your code must retry.
ClientRequestTokenmakes the call idempotent for a short window (10 minutes), so a network retry does not apply it twice.
Use transactions for invariants that span items (uniqueness, decrementing stock while creating an order line). Wrapping every write in one "to be safe" doubles your write cost for nothing.
Idempotency beyond transactions
Many writes come from at-least-once sources: SQS, Lambda retries, stream handlers, clients that retry after a timeout. Before doing the work, write an idempotency record PK = IDEMP#<request id> with attribute_not_exists(PK) and a TTL. If the put fails, you have seen this request; return the stored result. Powertools for AWS Lambda ships this pattern with DynamoDB as the store. Add conditional business writes ("set PAID only if PENDING") and duplicates become harmless.
Streams, TTL and capacity modes
DynamoDB Streams record every item change for 24 hours, ordered per item. A Lambda trigger reads them in batches. Use them for:
- Projections: keep a search index (OpenSearch), an analytics copy, or a denormalized view in sync. This is how you answer ad-hoc questions without scanning.
- The outbox pattern: write the order and its event in one transaction, then publish the event from the stream to EventBridge or SNS. The event is sent if and only if the write committed.
- Aggregates: maintain counters or totals in another item.
Handlers must be idempotent, and one bad record must not throw forever, or the whole shard stalls behind it. Configure a failure destination and partial batch responses.
TTL deletes items whose TTL attribute (an epoch seconds number) is in the past, at no write cost. Deletion is a background process and typically happens within a few days of expiry, not at the exact second. Expired-but-not-deleted items still come back from queries, so filter on the TTL attribute when exact expiry matters (sessions, tokens). TTL deletions appear in the stream, marked as performed by the DynamoDB service, so a stream handler can archive expired items to S3.
Capacity modes. On-demand needs no planning, and AWS cut its on-demand rates substantially in late 2024, so it is the sensible default for new tables. Provisioned with auto scaling suits steady traffic, but auto scaling reacts in minutes, so sharp spikes still throttle. Trust the current pricing page over old blog posts.
Single table or one table per entity?
Single-table design became famous because it lets one request fetch heterogeneous items (a customer and their orders) in one round trip. The honest trade-offs:
- For one table: fewer round trips for related data, one set of capacity and alarms, one stream to process, and it forces the access-pattern discipline above.
- Against: it is hard for newcomers to read, analytics and exports are awkward because rows have different shapes, and a late new pattern can mean backfilling key attributes across millions of items.
AWS's own guidance has softened: keep data that is accessed together in one table, and separate tables are fine for entities with unrelated access patterns or different lifecycles. A pragmatic rule: one table per service, never one table shared by services that deploy independently.
Sometimes the answer is not DynamoDB at all. As NoSQL Families and When to Use Them argues, choose Postgres when access patterns are unknown or changing, when you need ad-hoc reporting or joins, or when the data is relational and the scale is modest. DynamoDB shines with known patterns at high or spiky scale.
Order the steps of designing a DynamoDB table the way a senior would run it.
- Tap the steps below in the right order.
Match the requirement to the technique.
- access pattern
- A specific question the app asks of the data, with parameters and frequency. The input to DynamoDB key design.
- item collection
- All items sharing a partition key value, stored together and sorted by sort key, so one Query returns them.
- GSI overloading
- Using generic index key attributes so different item types serve different access patterns from one GSI.
- sparse index
- A GSI that only contains items that have its key attributes, used to index a small subset such as open orders.
- hot partition
- A partition receiving more traffic than its per-partition limit, usually because one key value is too popular.
- write sharding
- Spreading writes for one logical key across several keys with a suffix, then merging on read.
- optimistic locking
- Checking a version attribute in a condition expression so concurrent updates fail instead of overwriting each other.