Microservices are not classes and Object Oriented Programming should not be used for designing systems
tl;dr: when decomposing your business domain into microservices, use techniques like Domain-Driven-Design or Volatility-Based-Decomposition. Don’t just create a microservice for each domain entity and call it a day.
Designing a distributed system is hard. It’s hard because it requires us to go against some of the most basic things that we learned when we first started programming. Most people approach system design as if they were doing object-oriented programming, and it’s a big mistake. Here’s why:
Let’s take an e-commerce application. Many architects or developers would propose the following design:
Let’s focus on the Product Service. What does it do? At first glance, the following may seem like a good design: “the Product Service is responsible for all products in the system including price, name, pictures, description, stock, etc.”.
When we first learn Object-Oriented Programming, we are taught that classes are supposed to represent real-life entities: products, orders, users, etc. However, that approach doesn’t work when it comes to microservices. Your microservices are not supposed to represent real-life entities.
Imagine if you were building a house. You wouldn’t hire a kitchen expert, a living-room expert, a bathroom expert, and so on. You would hire an electrician, a plumber, a builder, etc.
You need a similar mindset when you design a system. You can’t just take your business domain and create a microservice for each domain entity. That’s like doing no design at all, which is why it’s so easy to do. Instead, you need to take time to design your system correctly. This goal will require you to analyze and understand your business domain and propose the right microservices decomposition. It’s easier said than done, which is why techniques like Domain-Driven Design and Volatility-Based Decomposition exist.
Going back to our Products Service, imagine that instead of having a single microservice that is responsible for everything to do with products, you would have:
- a Catalog Service, which would be responsible for products’ names, descriptions, images, etc…,
- an Inventory Service which would be responsible for everything to do with stock and product availability,
- a Pricing Service, which would be responsible for setting prices for the products,
You might ask, ‘Which service would be responsible for products?’. But it’s the wrong question. There isn’t one service that is responsible for everything to do with products, and that’s the point. We are not doing Object-Oriented Programming. We are doing System Design.