Uniqueness in DynamoDB secondary index
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Overview of Secondary Indexes in DynamoDB
Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. DynamoDB offers two types of secondary indexes: Global Secondary Indexes (GSI) and Local Secondary Indexes (LSI), which provide increased flexibility in querying your data. However, DynamoDB secondary indexes are often misunderstood in terms of uniqueness, as they do not natively enforce uniqueness on attributes other than the partition and sort keys.
What is a Secondary Index?
In DynamoDB, a secondary index is an optional, alternate, and explicitly declared view on your table that lets you query data efficiently using a key other than the primary key. Secondary indexes allow you to perform queries with different attribute combinations, enabling more complex querying capabilities.
Types of Secondary Indexes
Local Secondary Index (LSI)
- Definition: An LSI is an index that shares the same partition key as the table, but provides a different sort key. It allows you to create multiple attributes indexed with the shared partition key.
- Limitations: Each table can have a maximum of 5 LSIs. LSI must be created at the same time as the table.
Global Secondary Index (GSI)
- Definition: A GSI is an index with a completely separate partition and sort key from the base table. This allows for more flexible querying across any attribute.
- Limitations: Each table can have a maximum of 20 GSIs. GSIs can be added/removed at any time and are eventually consistent by default.
Uniqueness in DynamoDB Secondary Index
DynamoDB does not automatically enforce uniqueness on secondary index attributes unless they are part of the primary key. If you need unique values in a secondary index, you must implement custom logic. Below are techniques and workarounds to ensure uniqueness.
Enforcing Uniqueness on Secondary Indexes
- Composite Keys: Leverage composite keys with meaningful data concatenated to guarantee uniqueness effectively.
- Provisioned Capacity: Ensuring uniqueness might require additional read capacity, especially for queries before writes.
- Consistency Models: GSIs default to eventual consistency, making immediate uniqueness verification challenging. If strong consistency is necessary, careful design and usage of LSIs are advisable.
- Database Cost: Uniqueness checks can increase both the read and write durations, thereby inflating AWS costs.

