Home > Mobile >  .Net Core - AWS DynamoDb With Retry Policies
.Net Core - AWS DynamoDb With Retry Policies

Time:08-15

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?

CodePudding user response:

If you are using the .NET SDK for DynamoDb then you can do the following:

The to-be-decorated method

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"];
}

The retry policy

Trigger retry in case of throttling

var retry policy = Policy
  .Handle<ThrottlingException>()
  .Or<ProvisionedThroughputExceededException>()
  .WaitAndRetry(5, 
    retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
  );

Note

Please remember to use retry policy against idempotent operations

Decorate the method with the policy

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));
  • Related