I want to use retry pattern with Aws DynamoDb. I don't know if i can use the Polly
package from nuget. I researched a lot, but i learnt how to implement Polly but i couldn't find how to connect Polly with DynamoDb.
Is there any way to using Polly retry policies with Aws DynamoDb?
I'll give you an example code block and i want to know how to implement this with DynamoDb
Policy
.WaitAndRetryAsync(
5,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
(exception, timeSpan, context) => {
// do something
}
);
I am new with Aws Services, can you give me any suggestions?
If you are using the .NET SDK for DynamoDb then you can do the following:
Lets suppose you have simple point query like this:
public int GetAlternativeKey(int hashKey, string rangeKey)
{
var client = new AmazonDynamoDBClient();
var table = Table.LoadTable(client, "LookupTable");
var item = table.GetItem(hashKey, rangeKey);
return (int)item["Id"];
}
Trigger retry in case of throttling
var retry policy = Policy
.Handle<ThrottlingException>()
.Or<ProvisionedThroughputExceededException>()
.WaitAndRetry(5,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
);
Please remember to use retry policy against idempotent operations
If you have defined your to-be-decorated method (and the policy as well) as synchronous
policy.Execute(() => GetAlternativeKey(hk, rk));
If you have defined them as async
await policy.ExecuteAsync(async () => await GetAlternativeKey(hk, rk));
UPDATE #1
If I understood right, these are only errors I can have which you shared.
No, that's not true. These were just examples. Most of the exceptions that can be thrown by this library is inherited from the AmazonDynamoDBException
. Please see Inheritance Hierarchy section to get the full list of derived exceptions.
You talked about only use it against idempotent operations. Here what do you mean by idempotent operations? Are you suggesting me to only use retry policies with GET operations and not to use them in POST?
Idempotent operations do not cause any unwanted behaviour in case of re-execution (like duplicated inserts, multiple increment on a counter, etc.) In case of insert you can do a conditional check for not existence as a part of your putItem request. Please also check the Idempotency section of the documentation.