Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 70 ยท Databases

DynamoDB Data Modeling

Design DynamoDB tables from access patterns: single-table design, composite sort keys, GSIs and LSIs, hot partitions, TTL and streams, with runnable emulators.

In a relational database you model your data first and think about queries later: normalize the tables, then join whatever you need. DynamoDB works the other way around. It has no joins, and a query can only read items that share one partition key. So you start from the questions your application asks, and shape the keys so that each question becomes one cheap Query.

This lesson builds on DynamoDB Fundamentals, where you met tables, partition keys, sort keys and the difference between Query and Scan. Here you will learn how to design keys, when to use indexes, how to avoid hot partitions, and how TTL and streams fit in.

DynamoDB itself cannot run on this site, and there is no AWS account here. Table definitions and CLI calls below are read-only. The runnable examples are small Python emulators that follow the same key rules (partition key equality plus a sort key condition), so you can practice the modeling. They ignore capacity, pagination and many real features.

Start with access patterns

Before you create a table, write down every read and write the application needs. For a small shop, the list could be:

  1. Get a customer's profile.
  2. List a customer's orders, newest first.
  3. Get one order with its line items.
  4. List all orders that are currently in status SHIPPED.
  5. Remove abandoned carts automatically after a day.

Each item on that list needs an answer of the form "this key lookup or this key range". If you cannot express a pattern that way, you need another key layout, an index, or a different tool (for example search or analytics). That is the central rule of DynamoDB modeling: keys are designed for queries, not for entities.

Single-table design

A DynamoDB table can hold items of completely different shapes. Single-table design uses that to store related entities in the same partition, so one Query returns a customer and their orders together. You use generic key names (PK, SK) and put the entity type into the values:

PK SK Other attributes
CUSTOMER#c1 PROFILE name, email
CUSTOMER#c1 ORDER#2026-01-05#o100 total, status
CUSTOMER#c1 ORDER#2026-02-11#o101 total, status
ORDER#o100 ITEM#1 sku, quantity
ORDER#o100 ITEM#2 sku, quantity

The sort key does two jobs. Items in a partition are stored sorted by SK, so begins_with(SK, "ORDER#") returns just the orders, in date order, because the date comes right after the prefix. Reading them in reverse (ScanIndexForward=false) gives newest first.

flowchart LR
    subgraph P1["Partition key CUSTOMER#c1"]
        A["SK PROFILE"] --> B["SK ORDER#2026-01-05#o100"] --> C["SK ORDER#2026-02-11#o101"]
    end
    subgraph P2["Partition key ORDER#o100"]
        D["SK ITEM#1"] --> E["SK ITEM#2"]
    end

Items sharing a partition key are kept together and sorted by the sort key.

Here is a tiny emulator of that behavior. It stores items by (PK, SK) and supports the key-condition shapes DynamoDB allows: equality on PK, plus equality, begins_with or a range on SK.

Python Single-table design: three access patterns, one table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three different patterns are served by the same table with no scan. The fourth pattern from the list (orders by status, across all customers) cannot be answered by this layout, because status is not part of any key. That is what indexes are for.

Global and local secondary indexes

A global secondary index (GSI) is a second copy of selected attributes with a different key. DynamoDB maintains it automatically after each write. A GSI has its own partition key and optional sort key, its own capacity, and you can add or remove it at any time. Reads from a GSI are eventually consistent only: right after a write, the index may lag by a short time.

A local secondary index (LSI) keeps the table's partition key but gives you a different sort key. LSIs must be created together with the table, share the partition's capacity, and impose a 10 GB limit per partition key value. They support strongly consistent reads. Most designs today use GSIs, because they are more flexible.

Single-table designs usually add generic index attributes (GSI1PK, GSI1SK) to the items that need them. An item that lacks the index key attributes simply does not appear in the index, which is a handy way to build a sparse index.

Python A GSI for orders by status, plus TTL expiry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In real DynamoDB, TTL (time to live) works like the expires_at field here: you name a numeric attribute that holds an expiry time in epoch seconds, and DynamoDB deletes expired items in the background at no write cost. The deletion is not instant. It usually happens within a few days after expiry, so queries should also filter out expired items if exact timing matters.

Hot partitions

DynamoDB spreads items over partitions by hashing the partition key. Each partition can serve a limited rate (on the order of 3,000 read units and 1,000 write units per second). If most traffic hits one key value, for example PK = "STATUS#PENDING" for every order in a big shop, that partition becomes hot and requests are throttled even though the table as a whole has plenty of capacity.

Good partition keys have many distinct values with even traffic: customer IDs, order IDs, device IDs. For a key that is unavoidably popular, use write sharding: add a suffix so one logical key becomes several physical ones, and read all of them when you need the whole set.

Python Write sharding spreads a hot key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The trade-off is plain: writes spread out, but every read of the whole set becomes N queries. Use as few shards as the write rate requires.

Streams

A DynamoDB stream is an ordered log of item changes (inserts, updates, deletes) kept for 24 hours. Per item the order is preserved. You attach a Lambda function to react to changes: update a search index, send a welcome email, maintain a counter table. TTL deletions also show up in the stream, which is useful for archiving expired data. See Lambda Functions for how such a consumer is invoked.

Here is a creation call for a table with a GSI, TTL and a stream (read-only):

Terminal
aws dynamodb create-table \
  --table-name shop \
  --attribute-definitions AttributeName=PK,AttributeType=S AttributeName=SK,AttributeType=S \
      AttributeName=GSI1PK,AttributeType=S AttributeName=GSI1SK,AttributeType=S \
  --key-schema AttributeName=PK,KeyType=HASH AttributeName=SK,KeyType=RANGE \
  --global-secondary-indexes 'IndexName=GSI1,KeySchema=[{AttributeName=GSI1PK,KeyType=HASH},{AttributeName=GSI1SK,KeyType=RANGE}],Projection={ProjectionType=ALL}' \
  --billing-mode PAY_PER_REQUEST \
  --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES

aws dynamodb update-time-to-live \
  --table-name shop \
  --time-to-live-specification Enabled=true,AttributeName=expires_at

Backups, point-in-time recovery and global tables

A table design is only half of a production plan. The other half is "what if someone deletes the wrong items, and what if a whole Region fails?"

On-demand backups and point-in-time recovery

DynamoDB offers two kinds of backup, and both have no performance impact on the table:

  • On-demand backups are full snapshots that you start yourself (or schedule through AWS Backup). They are kept until you delete them, they are not tied to the table's lifetime, and they can be copied across Regions and accounts. Take one before a risky deployment or migration.
  • Point-in-time recovery (PITR) is continuous. Once you enable it, you can restore the table to any second in the last 35 days (the window is configurable). It protects against the most common disaster: a buggy script or a person that overwrote or deleted data.

A restore always creates a new table. It does not overwrite the original, so you can compare, copy the fixed items back, or switch your application to the restored table. Indexes, capacity settings, TTL and permissions may need to be re-applied, because they are not all restored automatically; check the documentation for the current list.

Terminal
aws dynamodb update-continuous-backups --table-name shop \
  --point-in-time-recovery-specification PointInTimeRecoveryEnabled=true

aws dynamodb restore-table-to-point-in-time \
  --source-table-name shop --target-table-name shop-restored \
  --restore-date-time 2026-11-10T08:59:30Z

aws dynamodb create-backup --table-name shop --backup-name before-migration

You can also export a table to S3 (DynamoDB JSON or Ion) from a PITR timestamp without using read capacity, which is the clean way to feed analytics with Athena (see Redshift and other analytics options).

Python What can PITR restore?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Global tables

A global table replicates a table across several AWS Regions, so users near each Region read and write locally, and the application survives the loss of a Region. It is multi-active: every replica accepts writes, and DynamoDB copies each change to the others, typically within a second. Creating one needs streams (enabled for you) and a replica per Region:

Terminal
aws dynamodb update-table --table-name shop \
  --replica-updates 'Create={RegionName=eu-west-1}'

Things to know:

  • If the same item is written in two Regions at nearly the same time, the conflict is resolved by last writer wins, using the write timestamps. Design so that conflicts are rare: route each user to one home Region, or keep write ownership per item.
  • Replication is eventually consistent across Regions. A strongly consistent read only sees the writes of its own Region.
  • You pay for storage in every Region and for replicated write capacity for every replica, so a global table with three Regions costs roughly three times the writes.
  • Each Region keeps its own backups and its own TTL deletions (which are replicated).
  • Combine global tables with Route 53 health checks or latency routing for failover (see Route 53 and High Availability and DR).

The stand-in shows last-writer-wins replication between two Regions with invented timestamps.

Python Last writer wins across Regions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

NoSQL Workbench

NoSQL Workbench is a free desktop application for DynamoDB. Its data modeler lets you define tables, keys, GSIs and sample items, then visualize how the access patterns map onto them, before you create anything in AWS. The operation builder helps you assemble queries and writes (and generate sample code), and can run them against DynamoDB Local or your real account. Models can be exported as CloudFormation or JSON. It fits the workflow of this lesson: list the access patterns, sketch the keys, load sample data, and check each pattern returns what you expect. See the CloudFormation lesson for deploying a resulting template.

When not to use single-table design

Single-table design is powerful but not free. The key layout is hard to read, and changing an access pattern later can mean rewriting data. Use it when your patterns are well known and performance at scale matters. For a small app with few entities, or a team that is still discovering its queries, several tables with simple keys are perfectly fine. If you need ad-hoc filtering, joins or reports, a relational database such as RDS is the better fit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the first step when designing a DynamoDB table?

    DynamoDB has no joins, so keys must be shaped around the queries you will run. Access patterns come first.
  2. 2. In a single-table design, why does the sort key often contain a prefix such as ORDER# followed by a date?

    Items in a partition are sorted by sort key, so a prefix selects a type of item and the date after it orders the results.
  3. 3. Which statement about global secondary indexes is correct?

    A GSI has its own partition and sort key, can be added later, and only supports eventually consistent reads. An LSI is the one that shares the partition key.
  4. 4. Almost every write in your table uses the partition key value "GLOBAL". What is the likely problem and a fix?

    One key value means one partition takes all the traffic. Use a high-cardinality key or shard the value into several.
  5. 5. When does a TTL expiry actually remove the item?

    TTL deletion is a free background process, not an exact timer.

Summary

  • Design DynamoDB tables from access patterns; each pattern should become one Query on a key or key range.
  • Single-table design stores related entities under one partition key and uses sort key prefixes (ORDER#...) to select and order them.
  • A GSI adds a different key schema, is eventually consistent and can be added any time; an LSI shares the partition key and must exist from table creation.
  • Avoid hot partitions with high-cardinality partition keys or write sharding.
  • TTL deletes expired items for free in the background; streams give an ordered 24-hour change log that Lambda can consume.

Next: ElastiCache, DocumentDB, Neptune and Redshift