Search code examples
javadomain-driven-designdomain-events

DDD - Architecture for Domain event storing and publishing


I'm implementing domain events framework for our application, below is the pseudo-code for the same, would like to know if there are any obvious caveats

The framework is to be designed 2 step, so as to persist the domain events(to reconstruct model state later incase required or we add say a reporting system to the mix may be) and the publishing infrastructure

Storing

begin txn
update model
Domaineventpublsisher.publish(event)
events serialized and stored to the persistence store by the Domaineventpublisher
commit txn

Publishing

timer triggers and the registered event dispatchers are notified
event dispatcher reads from of db unsent events
begin txn
the unsent events are published thro rabbitmq and persistence is updated with the last dispatched event
commit txn

this is the simplest one I could come up with based on a little bit of research, just did not want to overlook on anything.

Persistence is going to be connection pooled Postgres and as mentioned earlier RabbitMQ will be the messaging infra.


Solution

  • The first part is fine, since you are using the same DB for events and your model data. Thus, the transaction spans everything.

    You might have a problem with duplicated events in RabbitMQ though. Think of the following case:

    1. Your app publishes an event to RabbitMQ.
    2. RabbitMQ correctly receives the event.
    3. During the update of your local persistence, you app crashes.

    As a result, you will send the same events to RabbitMQ again after recovery. This effectively duplicates the event in RabbitMQ.

    This problem can usually be mitigated by having unique event IDs and/or performing de-duplication at the receiver side. You may also want to read the RabbitMQ reliability guide.