How do I choose the right primary key for a DynamoDB table?
Last updated: 2020-05-22
What should I consider when choosing a primary key for an Amazon DynamoDB table?
There are two types of primary keys in DynamoDB:
- Partition key: This is a simple primary key that's unique to each item in the table.
- Composite primary key: This is a combination of partition key and sort key, which is unique to each item in the table. For example, two items might have the same partition key, but they'll always have a different sort key.
No matter which type of primary key you choose, the primary key should always 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.