DynamoDB interview question · Most asked
How do you enforce uniqueness on an attribute that is not the primary key, such as email?
Summary
DynamoDB only guarantees uniqueness of the primary key. Create a separate item whose key is the unique value (PK = EMAIL#[email protected]) and write it together with the user item in a TransactWriteItems with attribute_not_exists(PK) conditions on both.
Longer Answer
If either condition fails the whole transaction is cancelled, so no duplicate is created even under concurrency. Changing the email means a transaction that deletes the old uniqueness item, creates the new one (with the condition) and updates the user. A GSI on email cannot enforce uniqueness because GSIs allow duplicate keys and update asynchronously.
Key Points
- Only the PK is unique.
- Extra 'uniqueness' item per value.
- Transaction with attribute_not_exists.
- GSIs cannot enforce uniqueness.
More most-asked DynamoDB questions
- What are DynamoDB Streams, and how are they used?
- Query or Scan: what is the difference, and why avoid Scan?
- What is DynamoDB, and what workloads is it a good fit for?
- What is a hot partition, and how do you avoid one?
- How do you approach data modelling in DynamoDB, and how is it different from relational design?
- Explain partition keys, sort keys and the two kinds of primary key.
- Global secondary index or local secondary index: what is the difference?
- How do conditional writes work, and how do you implement optimistic locking in DynamoDB?