DynamoDB
partition key
sort key
database design
AWS

What is the difference between partition key and sort key in amazon dynamodb?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

In Amazon DynamoDB, understanding the distinction between a partition key and a sort key is fundamental when designing tables to ensure efficient data retrieval and minimize costs. Both keys are integral to DynamoDB's unique method of storing and accessing data in a non-relational, highly-scalable, and performant manner.

Partition Key

Definition

A partition key is a single attribute that DynamoDB uses internally to distribute data across partitions. A partition is a segment of a table's data; the partition key maps items to specific partitions.

Characteristics

  • Single Attribute: The partition key consists of exactly one attribute.
  • Primary Role in Data Distribution: Determines how data is physically distributed across different partitions on disk.
  • Uniqueness: Within a table, each partition key value is unique per item. In a table without a sort key, the partition key uniquely identifies items.
  • Load Balancing: Ensures balanced distribution of data and workload across partitions, optimizing read/write performance.

Example

Consider a table `Customers` with a `CustomerID` as the partition key. Each `CustomerID` must be unique:

  • Composite Primary Key: Combines with the partition key to form a unique identifier for each item.
  • Enables Compound Sorting: Items with the same partition key can be sorted by the sort key.
  • Multi-Item Retrieval: Facilitates retrieval of related items through queries of the same partition key but different sort keys.
  • Equality on Partition Key: Must always be addressed in queries.
  • Range on Sort Key: Additional capabilities like sorting and filtering through conditions like "begins with," "between," etc.
  • Choosing a Suitable Partition Key: Selecting an evenly distributed partition key helps in maintaining read/write performance and cost effectiveness.
  • Compound Queries with Sort Key: By leveraging sort keys, applications can fetch subsets of items efficiently, optimizing query latency and throughput.
  • Identify attributes that naturally distribute data (e.g., user ID for partition key).
  • Use sort keys where varying attributes exist (e.g., timestamps, versions, or statuses), enabling complex query capabilities.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design