Guidance to use Parallel with DynamoDB #4299
-
|
I created a simple code to test a specific scenario that I'm facing using Lambda Function to use DynamoDB and Systems.Thread.Tasks.Parallel. If I run the following Parallel in 100 times, function is executed by no mistake. Out of memory in this scenario means that I opened too many sockets! I'd like to know if it's a best practice to use the Systems.Thread.Tasks.Parallel with AWS SDK. using System;
using System.Text;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
// Assembly attribute to enable Lambda function logging
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace ExampleLambda;
public class OrderHandler
{
private readonly IAmazonDynamoDB _dynamoClient;
public OrderHandler()
{
_dynamoClient = new AmazonDynamoDBClient();
}
public async Task<string> HandleRequest(OrderRequest request, ILambdaContext context)
{
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = 8
};
Parallel.For(0, 10000, parallelOptions, async i =>
{
try{
var getRequest = new GetItemRequest
{
TableName = "Orders",
Key = new Dictionary<string, AttributeValue>
{
{ "OrderId", new AttributeValue { S = $"ORDER-{i}" } }
}
};
await _dynamoClient.GetItemAsync(getRequest);
Console.WriteLine($"Querying item {i}");
}catch(Exception e){
Console.WriteLine(e);
}
});
return "Queries completed";
}
}
public class OrderRequest
{
public string Order { get; set; }
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
Either throttle with a semaphore + |
Beta Was this translation helpful? Give feedback.
-
|
As @AlexDaines said the I think all you have to do is change the |
Beta Was this translation helpful? Give feedback.
As @AlexDaines said the
Parallel.Fordoesn't await theActionpassed in so the10000iterations fire off immediately because as farParallel.Foris concerned the Action is over once you hit your firstawaitcall and then starts another one.I think all you have to do is change the
Parallel.FortoParallel.ForEachAsync. Don't forget toawaittheParallel.ForEachAsynccall.