Sponsorship is available! If you’d like to sponsor CodeOpinion.com and have your product or service advertised exclusively (no AdSense) on every post, contact me.
In service oriented architecture (including microservices) that leverage messaging, you’re going to run into both types of messages: Commands & Events. What’s the difference between Commands & Events? When should you use a command and when should use an event?
Check out my YouTube channel where I post all kinds of content that accompanies my posts including this video showing everything that is in this post.
What’s a Command?
Commands are messages with the intent to change the state of the system.
They are actions to be performed that have side effects.
They may be created by an end-user or another part of the system that could be automated.
They are away to execute behavior.
What’s an Event
Events are statements of fact.
They are named in the past tense because they represent something that has already occured.
Events are things that have happened within a system.
They are the result (not in the method/return sense) of an executed command.
They are notifications.
They are used to tell other parts of the system that something has occurred.
One important distinction between Commands & Events are consumers.
A command will have exactly one consumer. There will only be one consumer that will handle an instance of a command. When your producer sends a command to a message broker, it will send that command to only one consumer.
An event will have zero to many consumers. When a producer publishes an event to a message broker, it will deliver it to as many consumers that want it. Each consumer will receive a copy of the event. There may not be any consumers that want to receive an event. The publisher does not know who the consumers are, or how many of them exist for an event.
When to use a Command?
When you want to tell the system to perform some type of behavior. For example, sending a PlaceOrder command. You’re telling the system to perform an action that could have a side effect.
Name your commands like actions or tasks. They should be contain a verb.
When to use an Event?
When something has occurred as the result of a command and you want to tell other parts of the system. For example, OrderPlaced event can let other parts of the system know that an order has been placed. This likely would have resulted from a PlaceOrder command.
Because events are things that have occurred, they will be named in the past tense.
Commands & Events: Orchestration
You can leverage both commands and events together to orchestrate a business process or workflow. An orchestrator will send commands and consume the resulting events to kick off the next command.
Check out my blog post and video on Event Choreography & Orchestration (Sagas) for more details.