Managing data

Tracking a single order being placed is easy. However, multiply that number with the million orders being placed and canceled every hour; it could quickly become a challenge in the reactive microservices domain. The challenge is how you would perform a transaction across multiple services. Not only is it difficult to track such a transaction, but it poses other challenges, such as persisting such a transaction that spans the database and message broker. The task of reversing such an operation in the likelihood of the transaction breaking somewhere in the middle due to a service failure could be even more daunting.

In such a scenario, we can utilize the event sourcing pattern. This is a strong candidate, especially since we are not looking for a two-phase commit, generally referred to as 2PC. Instead of storing a transaction, we persist all the state-changing events of our entities. In other words, we store all the events that change their states in the form of entities, such as order and product. When a client places an order, then under regular circumstances, we would persist the order to the order table as a row. However, here we will persist the entire sequence of events, up to the final stage of the order being accepted or rejected.

Refer to the preceding diagram, where we analyzed the sequence of events that are generated while creating an order. Look at how those events will be stored in this pattern and how a transaction would be deduced from that set of events. First, let's see how the data will be stored. As seen in the following diagram, individual records are saved as rows. Data consistency is confirmed after the transaction:

As seen in the preceding diagram, the Product service can subscribe to the order events and update itself accordingly. There are numerous benefits to be derived from this approach, such as:

The following image is depicting our Order and Order Details table(s) in view of Order service:

Apart from all the benefits, it has some drawbacks as well. The most important one is how to query the event store. To reconstruct the state of a given business entity at a given point in time would require some complex queries. Apart from this, there would be a learning curve involved to grasp the concept of an event store replacing the database and then deducing the state of an entity. Query complexity can be handled with the help of the CQRS pattern easily. However, this will be outside the scope of this chapter. It is worthwhile to note that the event sourcing pattern and CQRS deserve separate chapters in the wake of reactive microservices.