domain-driven-designsoftware-design

Publish event in Domain Driven Design


Given that I have a project that uses Domain-Driven Design, and I have the following layers:

1: Domain

2: Application Service

3: Facade

4: Infrastructure

Now, let's consider a scenario where I have a command that creates something. I handle this command in my application service. After the creation process, I want to publish an event to an external service.

The question is:

Which layer is responsible for publishing the event?

What is the best practice in this context?

I would greatly appreciate it if you could provide any references on this matter.


Solution

  • The responsibility for publishing events is likely to be split across two layers:

    1. Domain - Your domain objects will be the ones determining what events are being fired and when.
    2. Infrastructure - Once you know what event will be published, the infrastructure layer is responsible for doing the actual integration with the other service or topic etc. that will deliver the event to its consumers.

    Splitting the responsibilities means that in future if you were to want to change your event tech from say RabbitMQ to Kafka, you'd only need to change the infrastructure (integration) component. Your domain would still behave the same and cause the same events to be published at the same time.

    -- Edit (added references and further explanation) --

    Microsoft's domain event documentation goes in to depth about when and how domain events can be raised. It references a preferred approach to raising events in a deferred manner described by Jimmy Bogard in this post.

    In terms of the integration with Kafka, all these integrations with systems external to the microservice itself (database, http clients, Kafka) can have their actual integration code written as a plugin service within the infrastructure layer. These services can be injected where needed, and swapped out for a newer version/different tech without affecting the domain logic.