Checking for existence of aggregate root instances

Hello Allard,

What are your recommendations to check for existence of aggregate root instances by business key? For example, when creating a user, one might want to check that the loginId is not taken already.

A few options:

  1. The client application makes sure that the loginId doesn’t exist by querying the read side
  2. The command handler checks for existence by querying the read side

Placing responsibility on the client seems a bit irresponsible. However, in a highly concurrent system, two users might try to create the same loginId or the same user might press the submit button more than once, and if the read side has not updated yet, the second attempt might erroneously succeed as well.

How are others dealing with such issues?


Hi Prem,

a common approach is to have the Command Handler perform a (quick) query. When an entry is found, the command is rejected. If no entry is found, there is a very small margin for error. In such a case, you would need to think about a compensating action. If two users register simultaneously with the same user ID, you could detect that in the handler updating the query you’re doing in the Command Handler. Then, simply block the second account.
You’ll need to figure out how big the chance of this happening is and how big the business impact is.

Assuming the risk is too big (i.e. impact * chance > acceptable threshold), you could create a registry where the command handling component would have to register their (unique) value before admitting the command. If a command fails, the entry is removed from the registry. It will put a bottleneck in the command handling for that specific command, but if the risk is too big, that should be worth it.