Sending an e-mail or SMS using CQRS and domain-driven-design - email

At this moment we are building a new architecture that is based on the principles of CQRS and domain-driven-design. We are now having some discussions about how we should deal with external communication. To make the question more concrete I use the example of sending a SMS notification when a customer creates a order.
The client creates a NewOrderCommand that is handled by the associated command handler. The handler creates a new Order object in the domain model, that generates a NewcustomerCreatedEvent. The object is saved in the event store and the event is published to all the listeners.
So far so good but now the question. Where should we sent out the SMS notification?
Our first instinct told us we should send it out by using a event listener that listens for the NewCustomerCreatedEvent and sends out the message. The problem with this approach is that the sending of the SMS is also part of our business logic. We are selling hosted services so our clients should be able to see all the SMS messages that are sent on their behalf. Because the sending of the message takes place outside of the domain we are not able to do that.
So we created an SMS domain and now when the event listener receives the NewCustomerCreatedEvent the event handler creates a new command SendSmsMessageCommand that will create a new SMSMessage object in our domain, sends out the SMS notification and creates a SmsSent event that we use to create the view.
At first we were sending the SMS message in the domain model, but we realized that this could give some problems. Let's say that after sending the SMS something happens (an exception is thrown) and the transaction is rolled back. Our domain supports this completely so data wise we are ok, but the SMS message is already sent, so when the command is resent the SMS notification will be sent again.
We were thinking about sending out the SMS on the SmSSent event but that would be a little bit strange, because the event says the message is already sent but is isn't.
The example above brings us to the question how to deal with external communication in the CQRS and domain-driven-design concept? We are not only talking about sending an SMS notification but also about sending an invoice to and external billing system and all other sort of communication to the outside world. Should we do this in the domain because it business logic or should we always do that based on events in our event handlers? And if we do so, is it acceptable to use events that say that the message is sent when it's not actually done yet?
Hope you guys have already dealt with this situation and can give us some advice on this subject.

I would think a domain object for the SMS message is not necessary. You just need to report the SMS's sent to the customer, correct? The SMS messages are not used in any domain logic, correct?
So I would have the handler send an SMS and then publish another event that says an SMS was sent and have an event handler listen for the SMS sent message and materialize that info in a read model so that the customer can view them.

You could use a Saga, or a Process Manager as Microsoft calls it. This basically listens to events, which change the saga's state, and issues commands based on the state logic implemented in the saga.
In your case it would be a two state saga, that waits for both CustomerCreatedEvent and OrderCreatedEvent, and, either issue a command to send an sms, if you have a specialised bounded context for communication, or call an infrastructure service, through an interface, to send the sms.
Here you can find Microsoft's article on the saga/process manager pattern:
https://msdn.microsoft.com/en-us/library/jj591569.aspx
And two articles containing implementations:
http://danielwhittaker.me/2015/03/31/how-to-send-emails-the-right-way-in-a-cqrs-system/
http://blog.jonathanoliver.com/cqrs-sagas-with-event-sourcing-part-ii-of-ii/

Related

What's the difference between the send and publish methods of Vertx's EventBus?

I'm having my first contact with Vertx's EventBus and I realized there are two ways to submit a message. Used the send or publish method. I ask: What is the practical difference between using these two methods and in what scenario do they use each one?
Both send and publish are used to send a message to an event bus address. However there are some differences between the two.
By using publish:
A message is sent to one or multiple listeners
All handlers listening against the address will be notified
No answer is expected from handlers
By using send:
A message is sent to one and only one handler registered against the event bus address.
If multiple handlers are registered, only one will be notified. The receiver will be selected by a "round-robin algorithm" as per the docs.
The receiver can answer the message, this answer can be empty or contain a response body. A response timeout can also be specified.
In practical usage, publish is quite useful to inform that an event has occured, whereas send is quite handy for asking a treatment where the response matters.
Conceptually, publish uses the publish/subscribe pattern whereas send uses the request/response pattern.

Mail notification from denormalized view in CQRS

I want to develop a mail notification service to send order approval to customer. The order data is in the denormalized view (query side) and it should be filled to the mail template. Then, we send the email in html string format via mail notification service. But, the order status should be changed to "order approval email sent".
I also try to implement the CQRS, ES, and DDD concept in microservices architecture.
Is this procedure correct and still align with the concept?
Develop HTTP POST API in order command to send approval mail so the order status could be changed in command-side.
The command side generate the event "order approval mail processed"
The event processor process the event. It should get the order data from query-side / denormalized view.
The event processor generates the approval mail from the data and fill the data to the template.
The event processor call HTTP POST to the mail notification service with mail body (html format) in the payload.
The event processor call HTTP PUT to the order service (command-side) to change the order status to "order approval mail sent".
But, if this procedure is applied, the user can't get the response "mail sent" in real-time. How to trigger the client / front-end side that the mail is successfully sent? So, the client side don't have a need to refresh or retry many calls to the API.
Thanks.
I've written a post on this subject a while ago, you can find it here: How to Send Emails the Right Way in a CQRS System
The short version is that I would use a process manager. A process manager listens to events and can issue commands as a result of these events. Just make sure you have a mechanism to not re-send emails if you ever re-run your events.
Regarding the UI. I have another post dealing with this question. You can find it here: 4 Ways to Handle Eventual Consistency on the UI
Here is a short answer. How often do you think once the code is run to send the email, that the email fails to send? Assuming you have a reasonably robust system, I would hope the vast majority of the time it would work. So fake it. And only if there is a problem find some way to notify the user and or admin users. If you want to get fancy you can use things like Signalr or some pub-sub framework for sending messages to the UI.
Anyway - hope that helps.

When should a confirmation email be sent after placing an order?

With regards an OMS, what is the best method to send a confirmation email? The 2 options I have so far are;
A script on the order page sends an email once the record is written to the database.
A scheduled task on the server, send the email, polling the database every-so-often to find new entries.
Which method do systems currently use?
For e-commerce websites, it might be better to think about the best user experience.
Given that, you would want to send the email as soon as the order is received so the user knows that they have purchased the item. The sooner it gets into their inbox, the sooner they will be happy that they have made their purchase.
I agree with Digbyswift that sending the confirmation email once the record is written to the database is the least scalable. But I would argue that if your system has gotten to the point that you are taking so many orders that your system cannot keep up, you have a wonderful problem on your hands that you now probably have resources to handle.
At PostageApp, we handle the emails of a few e-commerce websites, so perhaps you would benefit from an arrangement with an email service provider to off-load this task so that all of your resources can be spent on keeping your site up and your databases running.
Here are some great alternatives if PostageApp is not your style:
Sendgrid
Postmark
Mailjet
This is a question of scalability. Sending a confirmation email once the record is written to the database is the least scalable. The more orders that are taken , the more emails are sent potentially tying up resources.
A scheduled task is certainly better as emails can be queued up and can be sent in a separate process.
A further option which you could consider is using neither and delegating the responsibility of sending emails to a 3rd party dedicated emailing service, i.e. via an API. This is much better since your hosting does not have to consider the load and you can utilise any reporting offered by the 3rd party. Plus many services offer a free quota up to a certain threshold. This will allow you OMS and business to scale appropriately.
If you apply a message based architecture; you could just publish an order created message and have any number of subscribers respond to that event. You could create a listener that sends the email in house (bespoke option) or another listener that called the API of a 3rd party emailer to send the email on your behalf (as per #Digbyswift)
What I've always liked about this approach is
You can have any number of listeners live at any one time.
You can create a new listener and change how you send the email without needing to change/redeploy the OMS application itself.
You can take the listener(s) off line and stop / delay the sending of the email without losing any notifications or affecting the OMS itself.

MFMessageComposer iPhone,Auto Message Send

Any one know how to implement auto send message using MFMessageComposer....i mean No need of displaying The message Composer..we Have to sent the pre-defined message to a given Number..Or any other way without using MFMessageComposer..???
You can't auto-send messages with MFMessageComposer. It always displays the message to the user before sending (and rightly so).
An alternative would be to call a webservice which dispatches an email to you. Or put enough SMTP code in your app to get emails sending. You'll need your own email system for this though as you'll not be able to get the users email settings.

Send XMPP message without starting a chat

I am basically writing a XMPP client to automatically reply to "specific" chat messages.
My setup is like this:
I have pidgin running on my machine configured to run with an account x#xyz.com.
I have my own jabber client configured to run with the same account x#xyz.com.
There could be other XMPP clients .
Here is my requirement:
I am trying to automate certain kind of messages that I receive on gtalk. So whenever I receive a specific message eg: "How are you" , my own XMPP client should reply automatically with say "fine". How are you". All messages sent (before and after my client replies) to x#xyz.com but should be received by all clients (my own client does not have a UI and can only respond to specific messages.).
Now I have already coded my client to reply automatically. This works fine. But the problem I am facing is that as soon as I reply (I use the smack library), all subsequent messages that are sent to x#xyz.com are received only by my XMPP client. This is obviously a problem as my own client is quite dump and does not have a UI, so I don't get to see the rest of the messages sent to me, thereby making me "lose" messages.
I have observed the same behavior with other XMPP clients as well. Now the question is, is this is a requirement of XMPP (I am sorry but I haven't read XMPP protocol too well). Is it possible to code an XMPP client to send a reply to a user and still be able to receive all subsequent messages in all clients currently listening for messages? Making my client a full fledged XMPP client is a solution, but I don't want to go that route.
I hope my question is clear.
You may have to set a negative presence priority for your bot..
First thing to know is that in XMPP protocol every client is supposed to have a full JID. This is a bare JID - in your case x#xyz.com with a resource in the end e.g. x#xyz.com/pidgin or x#xyz.com/home (where /pidgin and /home are the resource). This is a part of how routing messages to different clients is supposed to be achieved.
Then there are the presence stanzas. When going online a client usually sends a presence stanza to the server. This informs about e.g. if the client is available for chat or away for lunch. Along with this information can be sent a priority. When there are more than one clients connected the one with the highest priority will receive the messages sent to the bare JID (e.g. ClientA(prio=50) and ClientB(prio=60) -> ClientB receives the messages sent to x#xyz.com). But there are also negative priorities. A priority less than 0 states that this client should never be sent any messages. Such a stanza might look like this
<presence from="x#xyz.com/bot">
<priority>-1</priority>
</presence>
This may fit your case. Please keep in mind it also depends on the XMPP server where your account is located, which may or may have not fully implemented this part of the protocol.
So to summarize: I recommend you to look through the Smack API how to set a presence and set the priority to <0 for your bot client right after it connected.