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 that 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);
}
}
}
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 scenarios, you will probably need a more advanced setup like the pseudo code in this blog post 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.