Auto retry concurrent commands with ncqrs
![Marco Franssen](/_next/image?url=%2Fimages%2Fprofile.jpg&w=96&q=75)
Marco Franssen /
2 min read • 284 words
![Cover Image for Auto retry concurrent commands with ncqrs](/_next/image?url=https%3A%2F%2Fog-image.vercel.app%2FAuto%2520retry%2520concurrent%2520commands%2520with%2520ncqrs.png%3Ftheme%3Dlight%26md%3D1%26fontSize%3D75px%26images%3Dhttps%253A%252F%252Fassets.vercel.com%252Fimage%252Fupload%252Ffront%252Fassets%252Fdesign%252Fvercel-triangle-black.svg%26widths%3Dauto%26heights%3Dauto&w=3840&q=75)
In a previous post I showed you some pseudo code Gregory Young mentioned in his DDD CQRS course I attended in Krakow, Poland. In this course Greg made clear to us locking of databases isn't necessary. He showed us some pseudo code how to easily write a merge handler to handle all concurrency conflicts.
In my current project, based on the ncqrs-framework I implemented a simpler version of this merge handler which only retries each command if a ConcurrencyException occurs. To achieve this you can easily build a wrapper around the ncqrs commandservice.
public class SafeCommandService : CommandService
{
public override void Execute(ICommand command)
{
try
{
base.Execute(command);
}
catch(ConcurrencyException ex)
{
Execute(command);
//Log retry executed
}
}
}
You can choose to implement this in a WCF service or whatever you want. Every command that fails will be retried until it succeeds. I have tested this with hundred async JavaScript calls which send a real simple command (PrintLabelCommand). My domain only processes a LabelPrintedEvent. When sending these calls to the server my log tells me there are only 8 retries average. This is acceptable in our situation. If you have more complex scenario's you will probably need a more advanced setup like the pseudocode in this blogpost shows you.
I'm still searching for a better name for my class, because SafeCommandExecutor isn't the best name I think. So let me know if you have a better one. I hope this article will be useful for you guys. As always, please share…
If you improved my code let me know, so I can learn from it.