KKeySync
← Back to quests
Quest · quest 11Johto · Advanced

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.

ConditionExpressionRace safetyItem existence

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.

Note: "Owner" is a reserved word in DynamoDB, so we use ExpressionAttributeNames (like #own) to map it safely!
Conditional Writejavascript

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.

Goal: Require 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.