Skip to content

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.

17 min read0/5 questions

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:

  1. List the entities and how they relate: customers, orders, order lines, products, warehouses.
  2. List every access pattern with its parameters and a rough frequency. Include writes, and include the boring ones.
  3. Design keys so each pattern maps to one call. Work from the most frequent pattern down.
  4. 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 patternFrequencyHow it is served
1Get product by idVery highGetItem PK=PRODUCT#p1, SK=META
2Get an order with its linesHighQuery PK=ORDER#o1
3Customer page: profile plus newest ordersHighQuery GSI1 PK=CUST#c1, descending
4A customer's orders in a date rangeMediumQuery GSI1 PK=CUST#c1, SK BETWEEN two dates
5Which orders contain product p1 (recalls)LowQuery GSI1 PK=PRODUCT#p1
6Open orders for a warehouse, oldest firstMediumQuery GSI2 PK=WH#lon (sparse)
7Sign up with an email that must be uniqueLowTransactWriteItems with attribute_not_exists
8Change an order's status without lost updatesMediumUpdateItem 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.

PKSKGSI1PKGSI1SKother
CUST#c1PROFILECUST#c1PROFILEname, email
ORDER#o1#METACUST#c1ORDER#2026-09-30#o1status, total, version
ORDER#o1ITEM#p1PRODUCT#p1ORDER#2026-09-30#o1qty, price
ORDER#o1ITEM#p2PRODUCT#p2ORDER#2026-09-30#o1qty, price
EMAIL#ada@example.comEMAILowner: c1

Things to notice:

  • Composite sort keys like ORDER#2026-09-30#o1 encode a hierarchy. ISO dates sort correctly as strings, so begins_with(SK, "ORDER#2026-10") means "October" and BETWEEN gives any range. The trailing id keeps keys unique when two orders share a date.
  • Sort order is a design tool. #META sorts before ITEM#... because # comes before letters in byte order, so the order header always comes back first. On GSI1, PROFILE sorts after ORDER#..., 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#12 answer "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.

Pythonsingle_table.py
class ConditionFailed(Exception): pass class Table: def __init__(self, gsis): self.items = {} # (PK, SK) -> item self.gsis = gsis # name -> (pk attribute, sk attribute) def put(self, item, must_not_exist=False, expect_version=None): key = (item["PK"], item["SK"]) old = self.items.get(key) if must_not_exist and old is not None: raise ConditionFailed(f"{key} already exists") if expect_version is not None and (old or {}).get("version") != expect_version: raise ConditionFailed(f"{key} version is not {expect_version}") self.items[key] = dict(item) def transact_put(self, puts): # All conditions are checked first; nothing is written unless all pass. for item, must_not_exist in puts: if must_not_exist and (item["PK"], item["SK"]) in self.items: raise ConditionFailed(f"transaction cancelled: {item['PK']} exists") for item, _ in puts: self.put(item) def query(self, pk, index=None, sk_begins="", sk_between=None, newest_first=False, limit=None, keep=None): pk_attr, sk_attr = self.gsis[index] if index else ("PK", "SK") # Only items that HAVE the index keys appear in an index (sparse indexes). rows = [i for i in self.items.values() if i.get(pk_attr) == pk and sk_attr in i] rows = [i for i in rows if i[sk_attr].startswith(sk_begins)] if sk_between: low, high = sk_between rows = [i for i in rows if low <= i[sk_attr] <= high] rows.sort(key=lambda i: i[sk_attr], reverse=newest_first) read = rows[:limit] if limit else rows # Limit counts items READ more = limit is not None and len(rows) > limit found = [i for i in read if keep is None or keep(i)] # filter runs after return found, more GSIS = {"GSI1": ("GSI1PK", "GSI1SK"), "GSI2": ("GSI2PK", "GSI2SK")}db = Table(GSIS) def sign_up(cid, name, email): db.transact_put([ ({"PK": f"CUST#{cid}", "SK": "PROFILE", "GSI1PK": f"CUST#{cid}", "GSI1SK": "PROFILE", "name": name, "email": email}, True), ({"PK": f"EMAIL#{email}", "SK": "EMAIL", "owner": cid}, True), ]) def place_order(oid, cid, date, warehouse, lines): total = sum(qty * price for _, qty, price in lines) db.put({"PK": f"ORDER#{oid}", "SK": "#META", "status": "PENDING", "total": total, "version": 1, "GSI1PK": f"CUST#{cid}", "GSI1SK": f"ORDER#{date}#{oid}", "GSI2PK": f"WH#{warehouse}", "GSI2SK": f"{date}#{oid}"}) for pid, qty, price in lines: db.put({"PK": f"ORDER#{oid}", "SK": f"ITEM#{pid}", "qty": qty, "price": price, "GSI1PK": f"PRODUCT#{pid}", "GSI1SK": f"ORDER#{date}#{oid}"}) def ship(oid, seen_version): order = dict(db.items[(f"ORDER#{oid}", "#META")]) order.update(status="SHIPPED", version=seen_version + 1) order.pop("GSI2PK", None); order.pop("GSI2SK", None) # leaves the sparse index db.put(order, expect_version=seen_version) sign_up("c1", "Ada", "ada@example.com")sign_up("c2", "Sam", "sam@example.com")place_order("o1", "c1", "2026-09-30", "lon", [("p1", 1, 40), ("p2", 2, 5)])place_order("o2", "c1", "2026-10-12", "lon", [("p2", 1, 5)])place_order("o3", "c2", "2026-10-14", "man", [("p1", 2, 40)]) def show(title, rows, *fields): print(f"-- {title}") for r in rows: print(" ", " | ".join(str(r.get(f, "")) for f in fields)) rows, _ = db.query("ORDER#o1")show("AP2 order o1 with its lines (one Query)", rows, "SK", "status", "qty", "total") rows, _ = db.query("CUST#c1", index="GSI1", newest_first=True)show("AP3 customer page: profile + newest orders (GSI1)", rows, "GSI1SK", "name", "total") rows, _ = db.query("CUST#c1", index="GSI1", sk_between=("ORDER#2026-10-01", "ORDER#2026-10-31~"))show("AP4 c1 orders in October (GSI1 range)", rows, "GSI1SK", "total") rows, _ = db.query("PRODUCT#p1", index="GSI1")show("AP5 orders containing p1 (inverted index)", rows, "PK", "qty") ship("o1", seen_version=1)rows, _ = db.query("WH#lon", index="GSI2")show("AP6 open orders in lon after shipping o1 (sparse GSI2)", rows, "GSI2SK", "status") for attempt in (lambda: sign_up("c3", "Eve", "ada@example.com"), lambda: ship("o1", seen_version=1)): try: attempt() except ConditionFailed as e: print("rejected:", e)print("customers:", sum(1 for k in db.items if k[1] == "PROFILE"))
Output
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, INCLUDE a list, or ALL. 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 GSI2PK while 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.

What happens on one write
Order serviceOrder serviceBase table: PK / SKBase tablePK / SKGSI1: by customer / productGSI1by customer / productGSI2 (sparse): open ordersGSI2 (sparse)open ordersDynamoDB Stream: 24 h of changesDynamoDB Stream24 h of changesLambda: projectorLambdaprojectorSearch / analyticsSearch / analyticsPutItem + conditionasyncasync, if keys presentchange recordbatches

The write goes to the base table. Any condition is evaluated here, atomically, against the current item. If it fails, nothing is written anywhere.

1/4
Quick check
A user creates an order, the API returns 201, and the client immediately fetches 'my orders' from a GSI keyed by customer. Sometimes the new order is missing. What is going on?
Need a nudge? A hint rules out a wrong answer.

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 as ExclusiveStartKey to get the next page. Your API should expose an opaque cursor built from it, not page numbers.
  • FilterExpression runs 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.
  • Limit is applied before the filter. Limit=20 means "read 20 items", not "return 20 matches". With a filter, you can get 3 items back, or zero, plus a LastEvaluatedKey. 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.
Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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:

  1. 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.
  2. 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#0 to #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.
  3. Cache hot reads in front of the table (DAX or ElastiCache) when one item is read thousands of times per second.
Quick check
A live-voting feature increments one counter item (PK = 'POLL#final', SK = 'COUNT') on every vote and is throttled during the show, while the table's total capacity is mostly unused. Which change actually fixes it?
Need a nudge? A hint rules out a wrong answer.

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:

sign_up.py
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.
  • ClientRequestToken makes 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.

Put it in order6 steps

Order the steps of designing a DynamoDB table the way a senior would run it.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/6 matched

Match the requirement to the technique.

Choose an item, then its match on the other side.
Key terms
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.