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

← All DynamoDB questions