Search code examples
domain-driven-designdomain-events

Domain driven design and domain events


I'm new to DDD and I'm reading articles now to get more information. One of the articles focuses on domain events (DE). For example sending email is a domain event raised after some criteria is met while executing piece of code.

Code example shows one way of handling domain events and is followed by this paragraph

Please be aware that the above code will be run on the same thread within the same transaction as the regular domain work so you should avoid performing any blocking activities, like using SMTP or web services. Instead, prefer using one-way messaging to communicate to something else which does those blocking activities.

My questions are

  1. Is this a general problem in handling DE? Or it is just concern of the solution in mentioned article?
  2. If domain events are raised in transaction and the system will not handle them synchronously, how should they be handled?
  3. When I decide to serialize these events and let scheduler (or any other mechanism) execute them, what happens when transaction is rolled back? (in the article event is raised in code executed in transaction) who will cancel them (when they are not persisted to database)?

Thanks


Solution

  • It's a general problem period never mind DDD

    In general, in any system which is required to respond in a performant manner (e.g. a Web Server, any long running activities should be handled asynchronously to the triggering process.

    This means queue.

    Rolling back your transaction should remove item from the queue.

    Of course, you now need additional mechanisms to handle the situation where the item on the queue fails to process - i.e the email isn't sent - you also need to allow for this in your triggering code - having a subsequent process RELY on the earlier process having already occurred is going to cause issues at some point.

    In short, your queueing mechanism should itself be transactional and allow for retries and you need to think about the whole chain of events as a workflow.