Architecture – Managing non-domain application behaviour in CQRS

Architecturecqrs

Here's a scenario.

I am building QueueUnderflow, a community-edited Q&A site for people who haven't yet grasped the basics of data structures. My users don't like it when people edit their posts so, because I want to encourage as much conflict as possible, I want to send email notifications whenever a user's post is edited so he can log in and insult the editor.

I am experimenting with CQRS. I'm not using event sourcing and have a single data store but I am using event handlers to deal with the persistence of any state changes.

In a normal N-Tier/CRUD app this might be triggered by an application facade or service layer. In my CQRS architecture, I can see a few options:

  1. The event handler: I like this idea because it seems that sending a notification email is a concern that could well lie with an independent part of the system that wants to listen for an appropriate time to send an email and then send it, transparent to the rest of the system. I dislike this idea because Greg Young (reasonably) points out in his videos that if I were to introduce event sourcing, this would result in the same notification emails being sent out potentially many times.
  2. The command handler: This is a more explicit approach that still makes sense to me; however, it seems that the general consensus is that command handlers should just be for coordinating domain objects and not directly performing behaviour.
  3. The domain: This seems plain wrong. The sending of notification emails is a concern of the application, not so much the domain which is concerned primarily with business logic.
  4. The presentation layer (or potentially some intermediate application facade that simply hands a command off to its handler and performs other application-specific actions such as sending notifications).

The question is – what part of my architecture is responsible for sending emails?

Best Answer

Number 1 jumps out as an elegant way to do this. Can you elaborate on why Event Sourcing would result in the same emails being sent multiple times ? ES systems normally have ways to distinguish between when an event is raised for the first time and when it is reapplied later. See line 90 of this code from one of Greg Young's repos.

2 . is also an option if you consider the command handler as an Application Service. Notification sending may be viewed as application-dependent -- if the applicative context is a UI-less batch program editing thousands of posts, maybe you don't want emails to be sent.

Related Topic