amazon-dynamodb

Transactional delete of parent item only if specific child items don't exist


I have a DynamoDB table with the following item structure:

PK: PARENT#<ID>, SK: PARENT#<ID>
PK: PARENT#<ID>, SK: CHILD_A#<ID>
PK: PARENT#<ID>, SK: CHILD_B#<ID>
PK: PARENT#<ID>, SK: CHILD_C#<ID>

I want to delete the parent item, but only if there are no CHILD_A# or CHILD_B# items present (I don't care about CHILD_C#). The challenge is that between checking for children and deleting the parent, another process could create a CHILD_A# or CHILD_B# item.

I need this operation to be atomic/transactional. Is there a way to:

  1. Check if CHILD_A# or CHILD_B# items exist
  2. Delete the parent only if they don't exist
  3. Ensure this happens atomically without race conditions

I've considered using a Query to check for children first, but this creates a race condition. Should I:

What's the best approach for this atomic conditional delete operation in DynamoDB?

As mentioned, I could Query for all child items of PARENT#<ID>, and then check if there are childs, and if not, then delete, but someone could create in the meantime a child. It's very rare, but still can happen.


Solution

    • Use a transaction with condition expressions?

    I don't think this will work because you won't know all possible sort keys for the potential child elements, so you won't be able to reference them in your transaction items.

    • Add a count attribute and use condition expressions on it?

    This should work. Increment / decrement a flag on the parent item when children are added / deleted, inside a transaction. Then use a condition on that count attribute when you delete the parent item.