Home > Enterprise >  Maintain 'Current Balance' in DDD Aggregate
Maintain 'Current Balance' in DDD Aggregate

Time:10-01

Working on an Inventory system.

Using C# and Entity Framework.

A StockItem will have many StockMovements. StockMovements could be a Purchase, Sale, Return, Wastage, etc.

A StockItem therefore has a StockLevel.

What is the best way to maintain StockLevel for a StockItem?

One way would be to just SUM all StockMovements when querying the StockItem, but if the number of StockMovements becomes excessive, it seems perhaps better to maintain a StockLevel on the StockItem and adjust it each time a StockMovement is added.

However, if two separate clients are processing a StockMovement at the same time, there is the possibility that two instance of the StockItem are materialised at the same time (i.e. both show balance of 100 units).

Client 1 removes 10 units and Client 2 also removes 10 units, but when updating the StockLevel, both StockItem instances will adjust the new StockLevel to 90, which is wrong. Should be 80.

So, using Optimistic Concurrency seems one option, but I don't want to push this back to the user.

Does it make sense for the Application layer to capture the concurrency exception and then retry on behalf of the client or are there any better patterns I should adopt?

CodePudding user response:

Use EF Core's Concurrency Tokens

Mark StockLevel as [ConcurrencyCheck], catch DbUpdateConcurrencyException as shown in Resolving concurrency conflicts

CodePudding user response:

you can use redis lock, because redis was single-threaded, just one request can processing for StockItem in the same time

  • Related