Catching Lugia (Conditional Writes)
You've encountered Lugia, the Guardian of the Seas! You throw a Master Ball, but what if another trainer threw one at the exact same millisecond? We don't want two trainers owning the exact same legendary instance in the database.
Key takeaways
- Condition Expressions enforce rules before writing to DynamoDB.
- UpdateItem can create a new item, so also assert that the target key exists.
- Conditional checks occur server-side, preventing race conditions.
Safe Legendary Catches
By adding a ConditionExpression to our UpdateItem call, we can tell DynamoDB: "Only assign ownership if this Lugia exists and has no owner." If someone else caught it a millisecond earlier, the condition fails and DynamoDB throws a ConditionalCheckFailedException.
ExpressionAttributeNames (like #own) to map it safely!Interactive Challenge
Two trainers might throw a Master Ball at the same instant. Make the catch safe by only writing the Owner if Lugia has no owner yet.
attribute_exists(Name) and attribute_not_exists(#own). This prevents both duplicate ownership and a phantom item if Lugia's key does not exist.Quick Quiz
What DynamoDB function checks if an attribute is missing before allowing a write?
Make your choice to test your understanding. Submit to check, and if it's not quite right you can adjust and try again.