The difference between a command and an event in bus communication seems a little vague to me. I know that commands should be executed once only, while an event can be handled multiple times, but still I'm not sure when to use a command or an event.
Let's look at an example:
When a new user registers to a web application, we should create him an account and send a confirmation email.
Creating the account – this seems to be the right spot to send a CreateUserCommand
to the bus and let a specialized component handle it.
Or maybe this shouldn't even be implemented with an asynchronous bus communication? We want the user to ba able to log in into the application right away. With the bus we have no guarantee when the command will be executed.
Sending email – after the component creates the account I can see 2 possibilities
- Send another command to the bus
SendConfirmationEmailCommand
- Publish an event
UserAccountCreatedEvent
And than let the email sender component grab it and to it's job.
On one hand I want the confirmation email to be sent once only (use a command), on the other hand, I believe there can be multiple components interested in newly registered users. A logger or maybe an SMS sender.
How would you implement it?
Best Answer
In principle, a command describes a request that is to be executed, whereas an event describes something that has happened:
A command requires some action to be performed by a processor, and this action should be performed only once by this processor.
An event is the notification of some action that was already executed or an external happening. Several processors/agents may be interested in knowing about the event. Several of them may further issue commands or action required by this notification in their domain of responsibility.
In your scenario, I understand that:
CreateUserCommand
is a commandUserAccountCreatedEvent
is an event that should be issued whenCreateUserCommand
is successfully completed by the account management serviceNow there are two possibilities:
SendConfirmationEmailCommand
on the bus, because it expects this command to be executed by a more specialized service.SendConfirmationEmailCommand
command to be performed by some gateway.If you have opted for a service bus approach, it would make sense to use the flexibility that this allows, i.e. to favor option 2.