How do I choose the right primary key for a DynamoDB table?

Last updated: 2020-12-18

What should I consider when choosing a primary key for an Amazon DynamoDB table?

Short description

There are two types of primary keys in DynamoDB:

  • Partition key: This is a simple primary key. If the table has only a partition key, then no two items can have the same partition key value.
  • Composite primary key: This is a combination of partition key and sort key. If the table has a composite primary key, then two items might have the same partition key value. However, those items must have different sort key values.

No matter what type of primary key you choose, the primary key must be unique for each item in the table. Failure to choose an appropriate primary key can lead to uneven data distribution and hot keys, which might cause throttling (ProvisionedThroughputExceededException).


Use one or more of the following strategies when choosing a primary key:

  • Use a high-cardinality attribute: The partition key should be an attribute that has unique values for each item, such as user ID, email, or phone number.
  • Use composite attributes: Combine multiple attributes to form a primary key. For example, you might have an "orders" table that combines the customer ID, product ID, and country code for the partition key, and then uses the order date as the sort key. This increases the likelihood that each item has a unique primary key.
  • Add random numbers to your partition key: For write-heavy use cases, consider adding random numbers from a predetermined range to your partition key. This increase the randomness of the partition key. For more information, see Using write sharding to distribute workloads evenly.

For detailed information about each of these strategies, see Choosing the right DynamoDB partition key.