You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Choosing the right primary key is the single most important design decision in DynamoDB. This lesson explains how partition keys and sort keys work, how DynamoDB distributes data, and how to design keys that enable efficient access patterns.
DynamoDB uses partitioning to distribute data across multiple storage nodes:
Hash Function
│
┌────────────────┼────────────────┐
▼ ▼ ▼
Partition A Partition B Partition C
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Items │ │ Items │ │ Items │
│ sorted by │ │ sorted by │ │ sorted by │
│ sort key │ │ sort key │ │ sort key │
└──────────┘ └──────────┘ └──────────┘
Each partition can store up to 10 GB of data and handle 3,000 read capacity units (RCUs) and 1,000 write capacity units (WCUs).
The partition key (also called the hash key) determines data distribution:
A good partition key has high cardinality — many distinct values that spread data evenly:
| Table | Good Partition Key | Why |
|---|---|---|
| Users | UserId | Unique per user |
| Orders | OrderId | Unique per order |
| IoT Readings | DeviceId | Many devices, even distribution |
| Sessions | SessionId | Unique per session (UUID) |
A bad partition key creates hot partitions — too many items on a single partition:
| Table | Bad Partition Key | Why |
|---|---|---|
| Orders | Status | Only a few values (Pending, Shipped, Delivered) |
| Events | Date | All today's events go to one partition |
| Users | Country | Uneven — most users may be in one country |
| Logs | LogLevel | Only ERROR, WARN, INFO, DEBUG |
Tip: If your natural key has low cardinality, consider adding a suffix (e.g.,
Date#ShardId) to spread the load.
The sort key (also called the range key) enables rich queries within a partition:
| Operator | Description | Example |
|---|---|---|
| = | Exact match | OrderDate = "2024-01-15" |
| <, <=, >, >= | Comparison | OrderDate > "2024-01-01" |
| BETWEEN | Range | OrderDate BETWEEN "2024-01-01" AND "2024-03-31" |
| begins_with | Prefix match | SK begins_with "ORDER#" |
You can encode hierarchies in sort keys using delimiters:
Table: Locations
Partition Key: Country
Sort Key: Region#City#Postcode
┌──────────┬───────────────────────────────┐
│ Country │ Sort Key │
├──────────┼───────────────────────────────┤
│ UK │ England#London#SW1A │
│ UK │ England#London#EC1A │
│ UK │ England#Manchester#M1 │
│ UK │ Scotland#Edinburgh#EH1 │
│ UK │ Wales#Cardiff#CF10 │
└──────────┴───────────────────────────────┘
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.