También conocido como Command Handler pattern
Comandos y Eventos
Los comandos capturan intención. El sistema hace algo cuando suceden. Si fallan, necesitamos mostrar un error. (CreateBatch)
Eventos ⇒ Broadcast. No sabemos quien los recibe. Los usamos para propagar facts que ocurrieron (BatchQuantityChanged)
| Event | Command | |
|---|---|---|
| Named | Past tense | Imperative mood |
| Error handling | Fail independently | Fail noisily |
| Sent to | All listeners | One recipient |
commands.Allocate will replace events.AllocationRequired
commands.CreateBatch will replace events.BatchCreated
NOTE
We don’t require the event handlers to succeed in order for the command to be successful.
Consistency
Cómo mantenes el sistema en un estado consistente? Qué pasa si no procesas un evento? Si la mitad de los eventos no se procesan porque te quedaste sin memoria?
Worst case
- Allocate 3 unidades de un artículo
- Falla al reducir el stock disponible
- Volves a allocate 3 unidades del mismo artículo que no tenes
La idea es evitar estos estados.
- Aggregates identify consistency boundaries
- UoW se encarga de la ejecución atómica de estos aggregates.
By definition, we don’t require two aggregates to be immediately consistent, so if we fail to process an event and update only a single aggregate, our system can still be made eventually consistent. We shouldn’t violate any constraints of the system.
Error handling
Qué deberíamos hacer entonces para recuperarnos de los errores?
- Saber cuándo pasó ⇒ Logs
- Manual replay del evento/command
- O mejor, “If at first you don’t succeed, retry the operation with an exponentially increasing back-off period”.
Splitting commands and events: Tradeoffs
| Pros | Cons |
|---|---|
| Treating commands and events differently helps us understand which things have to succeed and which things we can tidy up later. | The semantic differences between commands and events can be subtle. Expect bikeshedding arguments over the differences. |
CreateBatch is definitely a less confusing name than BatchCreated. We are being explicit about the intent of our users, and explicit is better than implicit, right? | We’re expressly inviting failure. We know that sometimes things will break, and we’re choosing to handle that by making the failures smaller and more isolated. This can make the system harder to reason about and requires better monitoring. |
| Chapter 11 - Event driven architecture |