The compensation pattern
Using our example of an Order and a Stock microservice from the previous section, we will now look at what happens if we have no stock to allocate for the order. These two microservices are decoupled, so do not share a traditional transaction boundary. We need a mechanism for the Stock microservice to inform the Order microservice that it could not allocate the required stock, and so it should reverse the confirmation. We will do this by again using events. The Stock microservice would publish an AllocationFailedEvent
and the Order microservice would subscribe to that event and revert the state of the order to pending.
We have applied this pattern to our application, as shown in the following diagram:
The preceding diagram shows the flow for a failure in transferring funds between accounts, as follows:
- The
AccountController
invokes thewithdraw
method on theAccountService...