The event-driven pattern

The microservice architecture has the database per service pattern, which means it has an independent database for every dependent or independent service:

The main challenge is to maintain business transactions to ensure data consistency across these services. For instance, when and how CUSTOMER-SERVICE would know that CHECKOUT-SERVICE has functioned; now it requires the functionality of CUSTOMER-SERVICE. There may be several services in an application (services may be self-hosted). In our case, when CHECKOUT-SERVICE is triggered and CUSTOMER-SERVICE is not invoked, then how will our application identify the customer’s details?

ASP.NET WebHooks can also be used for providing event notifications; refer to the WebHooks documentation for more information.

To overcome the related problems/challenges we've discussed (for CHECKOUT-SERVICE and CUSTOMER-SERVICE), we can use an event-driven pattern (or the eventual consistency approach) and use distributed transactions.

A document on MSDN (https://msdn.microsoft.com/en-us/library/windows/desktop/ms681205(v=vs.85).aspx) says the following:

A distributed transaction is a transaction that updates data on two or more networked computer systems. Distributed transactions extend the benefits of transactions to applications that must update distributed data. Implementing robust distributed applications is difficult because these applications are subject to multiple failures, including failure of the client, the server, and the network connection between the client and server. In the absence of distributed transactions, the application program itself must detect and recover from these failures.

The following diagram describes an actual implementation of the event-driven pattern in our application, where PRODUCT-SERVICE subscribes to the events and Event-Manager manages all the events:

In an event-driven pattern, we implement a service in such a way that it publishes an event whenever a service updates its data, and another service (dependent service) subscribes to this event. Now, whenever a dependent service receives an event, it updates its data. This way, our dependent services can get and update their data if required. The preceding diagram shows an overview of how services subscribe to and publish events. In the diagram, Event-Manager could be a program running on a service or a mediator helping you manage all the events of the subscribers and publishers.

It registers an event of the Publisher and notifies a Subscriber whenever a specific event occurs/is triggered. It also helps you to form a queue and wait for events. In our implementation, we will use Azure Service Bus queues for this activity.

Let's consider an example. In our application, this is how our services will publish and receive an event:

With the use of event-driven patterns, services can automatically update the database and publish an event.