82

Let's take a simple "Account Registration" example, here is the flow:

  • User visit the website
  • Click the "Register" button and fill out the form, click the "Save" button
  • MVC Controller: Validate UserName uniqueness by reading from ReadModel
  • RegisterCommand: Validate UserName uniqueness again (here is the question)

Of course, we can validate UserName uniqueness by reading from ReadModel in the MVC controller to improve performance and user experience. However, we still need to validate the uniqueness again in RegisterCommand, and obviously, we should NOT access ReadModel in Commands.

If we do not use Event Sourcing, we can query the domain model, so that's not a problem. But if we're using Event Sourcing, we are not able to query the domain model, so how can we validate UserName uniqueness in RegisterCommand?

Notice: User class has an Id property, and UserName is not the key property of the User class. We can only get the domain object by Id when using event sourcing.

BTW: In the requirement, if the entered UserName is already taken, the website should show the error message "Sorry, the user name XXX is not available" to the visitor. It's not acceptable to show a message, that says, "We are creating your account, please wait, we will send the registration result to you via Email later", to the visitor.

Any ideas? Many thanks!

[UPDATE]

A more complex example:

Requirement:

When placing an order, the system should check the client's ordering history, if he is a valuable client (if the client placed at least 10 orders per month in the last year, he is valuable), we make 10% off to the order.

Implementation:

We create PlaceOrderCommand, and in the command, we need to query the ordering history to see if the client is valuable. But how can we do that? We shouldn't access ReadModel in command! As Mikael said, we can use compensating commands in the account registration example, but if we also use that in this ordering example, it would be too complex, and the code might be too difficult to maintain.

sajadre
  • 1,141
  • 2
  • 15
  • 30
Mouhong Lin
  • 4,402
  • 4
  • 33
  • 48

8 Answers8

39

If you validate the username using the read model before you send the command, we are talking about a race condition window of a couple of hundred milliseconds where a real race condition can happen, which in my system is not handled. It is just too unlikely to happen compared to the cost of dealing with it.

However, if you feel you must handle it for some reason or if you just feel you want to know how to master such a case, here is one way:

You shouldn't access the read model from the command handler nor the domain when using event sourcing. However, what you could do is to use a domain service that would listen to the UserRegistered event in which you access the read model again and check whether the username still isn't a duplicate. Of course you need to use the UserGuid here as well as your read model might have been updated with the user you just created. If there is a duplicate found, you have the chance of sending compensating commands such as changing the username and notifying the user that the username was taken.

That is one approach to the problem.

As you probably can see, it is not possible to do this in a synchronous request-response manner. To solve that, we are using SignalR to update the UI whenever there is something we want to push to the client (if they are still connected, that is). What we do is that we let the web client subscribe to events that contain information that is useful for the client to see immediately.

Update

For the more complex case:

I would say the order placement is less complex, since you can use the read model to find out if the client is valuable before you send the command. Actually, you could query that when you load the order form since you probably want to show the client that they'll get the 10% off before they place the order. Just add a discount to the PlaceOrderCommand and perhaps a reason for the discount, so that you can track why you are cutting profits.

But then again, if you really need to calculate the discount after the order was places for some reason, again use a domain service that would listen to OrderPlacedEvent and the "compensating" command in this case would probably be a DiscountOrderCommand or something. That command would affect the Order Aggregate root and the information could be propagated to your read models.

For the duplicate username case:

You could send a ChangeUsernameCommand as the compensating command from the domain service. Or even something more specific, that would describe the reason why the username changed which also could result in the creation of an event that the web client could subscribe to so that you can let the user see that the username was a duplicate.

In the domain service context I would say that you also have the possibility to use other means to notify the user, such like sending an email which could be useful since you cannot know if the user is still connected. Maybe that notification functionality could be initiated by the very same event that the web client is subscribing to.

When it comes to SignalR, I use a SignalR Hub that the users connects to when they load a certain form. I use the SignalR Group functionality which allows me to create a group which I name the value of the Guid I send in the command. This could be the userGuid in your case. Then I have Eventhandler that subscribe to events that could be useful for the client and when an event arrives I can invoke a javascript function on all clients in the SignalR Group (which in this case would be only the one client creating the duplicate username in your case). I know it sounds complex, but it really isn't. I had it all set up in an afternoon. There are great docs and examples on the SignalR Github page.

Mikael Östberg
  • 16,982
  • 6
  • 61
  • 79
  • What should I do in the compensating command when I find that the username is duplicate? Publish a SignalR event to inform the client that the username is not available? (I haven't used SignalR, I guess there might be some kind of "events?) – Mouhong Lin Feb 29 '12 at 09:21
  • Great answer, thanks! But I'm a bit confused by the "domain service", did you mean "event handlers"? I think it's not same as the "Domain Service" in DDD? – Mouhong Lin Feb 29 '12 at 13:00
  • 1
    I think we called it Application Service in DDD, but I might be mistaken. And also, domain service is a debated term in the DDDD/CQRS community. However, what you need is something similar to what they call Saga except that you probably wont need state nor a state machine. You just need something that can react and feed off of events, perform data lookup and dispatch commands. I call them domain services. In short, you subscribe to events and send commands. That's useful when communicating between Aggregate Roots as well. – Mikael Östberg Feb 29 '12 at 14:48
  • 1
    I should also mention that I have my domain services in a completely different process, separated from for example the read models. This makes messaging related stuff simpler to deal with, such as subscriptions and such. – Mikael Östberg Feb 29 '12 at 14:54
  • 1
    This is a great answer. However, I see this comment a lot "You shouldn't access the read model from the command handler nor the domain when using event sourcing". Can someone explain why it's such a bad idea to use the read model from within the command/domain side. Is this the point of command/query segregation? – Scott Coates Sep 11 '12 at 08:50
  • 1
    The combination of domain state and the command must be sufficient for the decision. If you feel you need to read data when handling commands, bring that data with you in the command or store it in the domain state. And why? - The read store is eventual consistent, it may not have the truth. The domain state is the truth and the command completes it. - If you're using ES, you can store the command along with the event(s). This way, you see exactly what information you were acting on. - If you read beforehand, you can perform validation and increase your command's probability of success. – Mikael Östberg Sep 11 '12 at 12:25
  • _It is just too unlikely to happen compared to the cost of dealing with it._ If it's possible, it will happen (f.e. event bus has a huge delay because of network issues or to many registrations at one time, thus the user tries again). Imagine having one user registered twice in your system and one day he/she generates content with account 1 and the other day with account 2. After some time they'll ask you to merge both accounts AND its content. Good luck fixing the eventstore and trying to charge the customer for that :) – huysentruitw May 31 '17 at 13:48
  • Just a small note, if we are talking about user registration case. Compensating command should be UnRegisterUser or so. Not ChangeUserName. Also in async world accessing readmodel still will not give you the truth. So another option would be store all user names combinations inside some aggregate. That will be a heavy one but will eliminate round trip to readmodels. – Tenek Aug 30 '18 at 22:40
26

I think you are yet to have the mindset shift to eventual consistency and the nature of event sourcing. I had the same problem. Specifically I refused to accept that you should trust commands from the client that, using your example, say "Place this order with 10% discount" without the domain validating that the discount should go ahead. One thing that really hit home for me was something that Udi himself said to me (check the comments of the accepted answer).

Basically I came to realise that there is no reason not to trust the client; everything on the read side has been produced from the domain model, so there is no reason not to accept the commands. Whatever in the read side that says the customer qualifies for discount has been put there by the domain.

BTW: In the requirement, if the entered UserName is already taken, the website should show error message "Sorry, the user name XXX is not available" to the visitor. It's not acceptable to show a message, say, "We are creating your account, please wait, we will send the registration result to you via Email later", to the visitor.

If you are going to adopt event sourcing & eventual consistency, you will need to accept that sometimes it will not be possible to show error messages instantly after submitting a command. With the unique username example the chances of this happening are so slim (given that you check the read side before sending the command) its not worth worrying about too much, but a subsequent notification would need to be sent for this scenario, or perhaps ask them for a different username the next time they log on. The great thing about these scenarios is that it gets you thinking about business value & what's really important.

UPDATE : Oct 2015

Just wanted to add, that in actual fact, where public facing websites are concerned - indicating that an email is already taken is actually against security best practices. Instead, the registration should appear to have gone through successfully informing the user that a verification email has been sent, but in the case where the username exists, the email should inform them of this and prompt them to login or reset their password. Although this only works when using email addresses as the username, which I think is advisable for this reason.

Community
  • 1
  • 1
David Masters
  • 8,069
  • 2
  • 44
  • 75
  • 3
    Excellent input. It's the mind that have to change before the system can (I didn't intend to sound like Yoda there). – Mikael Östberg Feb 29 '12 at 21:06
  • 6
    +1 Just being *really* pedantic here...ES & EC are 2 completely different things and using one shouldn't imply using the other (although, in most cases it makes perfect sense). It's perfectly valid to use ES without having an eventually consistent model and vice versa. – James May 01 '14 at 14:33
  • "Basically I came to realise that there is no reason not to trust the client" - yes I think this is a fair comment. But how does one handle external access that might be producing commands? Clearly we don't want to allow a PlaceOrderCommand with a discount that is automatically applied; the application of a discount is domain logic, not something that we can "trust" someone to tell us to apply. – Stephen Drew May 17 '14 at 07:35
  • 3
    @StephenDrew - Client in this context just means whatever unit of code is producing the command. You may (and perhaps should) have a layer before the command bus. If you were making an external web service, the mvc controller that places an order would first do the query and then submit the command. The client here is your controller. – ryeguy Sep 14 '14 at 01:11
  • 5
    Taking your response close to heart, would mean that all the theory around "Invariants", "Business Rules", "High Encapsulation" is absolute nonsense. There are too many reasons why to not trust the UI. And after all UI is not a mandatory part...what if there is no UI? – Cristian E. Mar 05 '17 at 23:17
  • @David Masters how about if I need to check product number existed or not – minhhungit Jul 10 '21 at 19:08
23

There is nothing wrong with creating some immediately consistent read models (e.g. not over a distributed network) that get updated in the same transaction as the command.

Having read models be eventually consistent over a distributed network helps support scaling of the read model for heavy reading systems. But there's nothing to say you can't have a domain specific read model thats immediately consistent.

The immediately consistent read model is only ever used to check data before issuing a command, you should never use it for directly displaying read data to a user (i.e. from a GET web request or similar). Use eventually consistent, scaleable read models for that.

GWed
  • 15,167
  • 5
  • 62
  • 99
11

About uniqueness, I implemented the following:

  • A first command like "StartUserRegistration". UserAggregate would be created no matter if user is unique or not, but with a status of RegistrationRequested.

  • On "UserRegistrationStarted" an asynchronous message would be sent to a stateless service "UsernamesRegistry". would be something like "RegisterName".

  • Service would try to update (no queries, "tell don't ask") table which would include a unique constraint.

  • If successful, service would reply with another message (asynchronously), with a sort of authorization "UsernameRegistration", stating that username was successfully registered. You can include some requestId to keep track in case of concurrent competence (unlikely).

  • The issuer of the above message has now an authorization that the name was registered by itself so now can safely mark the UserRegistration aggregate as successful. Otherwise, mark as discarded.

Wrapping up:

  • This approach involves no queries.

  • User registration would be always created with no validation.

  • Process for confirmation would involve two asynchronous messages and one db insertion. The table is not part of a read model, but of a service.

  • Finally, one asynchronous command to confirm that User is valid.

  • At this point, a denormaliser could react to a UserRegistrationConfirmed event and create a read model for the user.

Daniel Vasquez
  • 111
  • 1
  • 3
  • 2
    I do something similiar. In my event sourced system, I have a UserName aggregate. It's AggregateID is the UserName I would like to register. I issue a command to register it. If it is already registered, we get an event. If it is available, then it is immediately registered and we get an event. I try to avoid "Services" as they sometimes feel as though there is a modeling flaw in the domain. By making a UserName a first class Aggregate, we model the constraint in the domain. – CPerson Jun 24 '19 at 13:22
8

Like many others when implementing a event sourced based system we encountered the uniqueness problem.

At first I was a supporter of letting the client access the query side before sending a command in order to find out if a username is unique or not. But then I came to see that having a back-end that has zero validation on uniqueness is a bad idea. Why enforce anything at all when it's possible to post a command that would corrupt the system ? A back-end should validate all it's input else you're open for inconsistent data.

What we did was create an index table at the command side. For example, in the simple case of a username that needs to be unique, just create a user_name_index table containing the field(s) that need to be unique. Now the command side is able to query a username's uniqueness. After the command has been executed it's safe to store the new username in the index.

Something like that could also work for the Order discount problem.

The benefits are that your command back-end properly validates all input so no inconsistent data could be stored.

A downside might be that you need an extra query for each uniqueness constraint and you are enforcing extra complexity.

Jonas Geiregat
  • 5,214
  • 4
  • 41
  • 60
7

I think for such cases, we can use a mechanism like "advisory lock with expiration".

Sample execution:

  • Check username exists or not in eventually consistent read model
  • If not exists; by using a redis-couchbase like keyvalue storage or cache; try to push the username as key field with some expiration.
  • If successful; then raise userRegisteredEvent.
  • If either username exists in read model or cache storage, inform visitor that username has taken.

Even you can use an sql database; insert username as a primary key of some lock table; and then a scheduled job can handle expirations.

Safak Ulusoy
  • 319
  • 3
  • 7
2

Have you considered using a "working" cache as sort of an RSVP? It's hard to explain because it works in a bit of a cycle, but basically, when a new username is "claimed" (that is, the command was issued to create it), you place the username in the cache with a short expiration (long enough to account for another request getting through the queue and denormalized into the read model). If it's one service instance, then in memory would probably work, otherwise centralize it with Redis or something.

Then while the next user is filling out the form (assuming there's a front end), you asynchronously check the read model for availability of the username and alert the user if it's already taken. When the command is submitted, you check the cache (not the read model) in order to validate the request before accepting the command (before returning 202); if the name is in the cache, don't accept the command, if it's not then you add it to the cache; if adding it fails (duplicate key because some other process beat you to it), then assume the name is taken -- then respond to the client appropriately. Between the two things, I don't think there'll be much opportunity for a collision.

If there's no front end, then you can skip the async look up or at least have your API provide the endpoint to look it up. You really shouldn't be allowing the client to speak directly to the command model anyway, and placing an API in front of it would allow you to have the API to act as a mediator between the command and read hosts.

Sinaesthetic
  • 11,426
  • 28
  • 107
  • 176
2

It seems to me that perhaps the aggregate is wrong here.

In general terms, if you need to guarantee that value Z belonging to Y is unique within set X, then use X as the aggregate. X, after all, is where the invariant really exists (only one Z can be in X).

In other words, your invariant is that a username may only appear once within the scope of all of your application's users (or could be a different scope, such as within an Organization, etc.) If you have an aggregate "ApplicationUsers" and send the "RegisterUser" command to that, then you should be able to have what you need in order to ensure that the command is valid prior to storing the "UserRegistered" event. (And, of course, you can then use that event to create the projections you need in order to do things such as authenticate the user without having to load the entire "ApplicationUsers" aggregate.

  • 1
    This is exactly how you have to think about Aggregates. The purpose of an Aggregate is to protect against concurrency/inconsistency (you have to guarantee this through some mechanism in order for it to be an Aggregate). When you think about them this way, you also realize the cost of protecting the invariant. In the worst case scenario in a highly contentious system, all messages to the Aggregate would have to be serialized and handled by a single process. Does this conflict with the scale you're operating at? If so, you should reconsider the value of the invariant. – Andrew Larsson Jul 08 '19 at 17:03
  • 4
    For this specific scenario with usernames, you can still achieve uniqueness while being horizontally scalable. You can partition your username registry Aggregates along the first N characters of the username. For example, if you have to handle thousands of concurrent registrations, then partition along the first 3 letters of the username. So, to register for the username "johnwilger123" you would address the message to the Aggregate instance with ID "joh" and it can check its set of all "joh" usernames for uniqueness. – Andrew Larsson Jul 08 '19 at 17:09