EduBw
EduBw

Reputation: 942

Rollback with DynamoDb?

I have a question, If I insert in DynamoDb 5 o 6 elements, but for example 6º fail. How can I do rollback in dynamoDb ?

    MyMessage myMessage = new MyMessage(true, "ok");
    Article art;

    for (int i = 0; i < list.size(); i++) {
        art= (Article) list.get(i);
        try {
            this.artRepository.save(art);
        } catch (Exception e) {
            myMessage.setSuccess(false);
            myMessage.setMessage("Fail.");
        }
    }

    if(myMessage.isSuccess()) {
        artRepository.save..
    }else{
      Rollback.
    }

Upvotes: 5

Views: 13940

Answers (2)

ylev
ylev

Reputation: 2569

See a good C# transaction example at: AWS DynamoDb Transactions in C# And also a Java example:

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-example.html

They arrange a list of TransactWriteItem of 3 types ConditionCheck, Update and Put (for insert). Note: There is also a "Delete" type.

List<TransactWriteItem> actions = new()
{
    new TransactWriteItem() {ConditionCheck = checkCustomerValid },
    new TransactWriteItem() { Update = markItemSold },
    new TransactWriteItem() { Put = createOrder }
};

Wrap the items in TransactWriteItemsRequest object:

TransactWriteItemsRequest placeOrderTransaction = new()
{
    TransactItems = actions, // <<== the list from above
    ReturnConsumedCapacity = ReturnConsumedCapacity.TOTAL
};

And Run the transaction:

AmazonDynamoDBClient client = new();
await client.TransactWriteItemsAsync(placeOrderTransaction);

Upvotes: 0

tleef
tleef

Reputation: 3594

Edit: DynamoDB now supports transactions.

DynamoDB has two new API operations TransactWriteItems and TransactGetItems

Using these operations you can perform ACID transactions on a DynamoDB Table.

More details here

Old answer

DynamoDB doesn't support this transactional behavior.

First, you shouldn't be making multiple requests in a for loop like that. It is a waste of network resources. You would do better to use a batch request. Keep in mind, the items in a batch request are still independent and may fail independently from one another.

If you need to support this type of behavior with Dynamo, you can look at using a more durable method of inserting your documents such as first putting them into SQS or Kinesis (Both of which also support batch requests). You can then reliably retry if an insert fails. In the case of repeated failures, you can use a Dead Letter Queue and even have the item sent to SNS to trigger an alert of some sort.

If you need the transaction to be enforced by the DB for consistency reasons, you should look at using a SQL database.

Upvotes: 5

Related Questions