1

I am working on an application written in Flask and backed by Amazon's DynamoDB accessed through boto.

For a specific use case, we need to retrieve a value from a table and then make it unavailable for other users.

However, by retrieving and then deleting the value, a race-condition could occur in between the retrieval and deletion.

Is there any way to retrieve an item from a table and immediately delete or update it in an atomic fashion?

0x90
  • 6,079
  • 2
  • 36
  • 55

1 Answers1

2

If your logic:

  1. get item
  2. delete

without any additional logic to determine whether deletion should occur, then you can actually send delete request immediately, here is example (I haven't checked it, mostly take from: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelJavaItemCRUD.html)

HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("101"));

DeleteItemRequest deleteItemRequest = new DeleteItemRequest()
    .withTableName(tableName)
    .withKey(key)
    .withReturnValues(ReturnValue.ALL_OLD);

DeleteItemResult deleteItemResult = client.deleteItem(deleteItemRequest);
Map<String,AttributeValue> deletedItem = deleteItemResult.getAttributes();

Documentation:

withReturnValues

getAttributes

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
  • Is there a race condition possibility here? IIRC you can select a DynamoDB option of read after write consistency, so of you pay more that might work (error on the second delete...) – Andy Hayden Oct 30 '17 at 23:42
  • @AndyHayden AFAIR, if you use read operation it could potentially return deleted item, but if you use delete operations it should be strongly consistent. Or you can force them to be consistent by using conditional expressions, like `id=101` – Iłya Bursov Oct 31 '17 at 00:56