Materialized View Pattern
In this tutorial, we are going to talk about Design Patterns of Microservices architecture which is the Materialized View Pattern. We will use this pattern and practice when designing e-commerce microservice architecture.
Let me start with the problem. Think about that we have a use case that is “add item into shopping cart” use case of our e–commerce microservices application. You can see the illustration in the below image.
According to the image we have “Shopping Cart”, “Catalog” and “Pricing” microservices. And if the user adds an item into the basket, how these microservices should interact with each other?
Should ShoppingCart microservice query product data and price information to other microservices with sync calls? Or is there any other way to handle this problem? And also what if we have transactional use cases that need to interact with several services with rollback features?
In order to solve the questions, We will see patterns and principles for these problems. We will solve this problem with “Materialized View Pattern”.
Materialized View Pattern
So at that stage, Materialized View Pattern is a very good option for this problem. Materialized View Pattern is recommended to store its own local copy of data in the microservice.
In our case, the shopping car microservice should have a table that contains a denormalized copy of the data needed from the product and pricing microservices. We can also be called this local copy of data a Read Model. That’s why the name of the pattern is Materialized View Pattern.
So Instead of the Shopping Basket microservice querying the Product Catalog and Pricing microservices, it maintains its own local copy of that data. In this way, the Shopping Cart (SC) microservice eliminates the synchronous cross-service calls.
And also this makes SC microservice is more resilient, because if SC tries to call catalog and pricing microservices and if one of the services is down, then the whole operation could be blocked or rollback. So this pattern broke the direct dependency of other microservices and make faster the response time.
Drawbacks of Materialized View Pattern
But this pattern has also drawbacks that we have to consider and make sure of when deciding to implement this pattern.
Because the source of data is other microservices and when the original data changes it should update into SC microservices. There are several ways to handle this problem like using message broker systems, when data is changed in the original microservices publish an event and consume it from the subscriber microservice in order to update its denormalized table. Another way can be using a scheduled task, an external trigger, or a manual action to regenerate the table.
As you can see that we have learned Materialized View Pattern in one of the use cases which is adding items into the shopping cart.