In this section, we will examine some of the principles of the microservices architecture. These principles are a must have when designing and developing microservices. The two key principles are single responsibility and autonomous.
Principles of microservices
Single responsibility per service
The single responsibility principle is one of the principles defined as part of the SOLID design pattern. It states that a unit should only have one responsibility.
Read more about the SOLID design pattern at http://c2.com/cgi/wiki?PrinciplesOfObjectOrientedDesign.
It implies that a unit, either a class, a function, or a service, should have only one responsibility. At no point do two units share one responsibility, or one unit perform more than one responsibility. A unit with more than one responsibility indicates tight coupling:
As shown in the preceding diagram, Customer, Product, and Order are different functions of an e-commerce application. Rather than building all of them into one application, it is better to have three different services, each responsible for exactly one business function, so that changes to one responsibility will not impair the others. In the preceding scenario, Customer, Product, and Order were treated as three independent microservices.
Microservices are autonomous
Microservices are self-contained, independently deployable, and autonomous services that take full responsibility of a business capability and its execution. They bundle all dependencies including the library dependencies; execution environments, such as web servers and containers; or virtual machines that abstract the physical resources.
One of the major differences between microservices and SOA is in its level of autonomy. While most of the SOA implementations provide the service-level abstraction, microservices go further and abstract the realization and the execution environment.
In traditional application developments, we build a war or a ear, then deploy it into a JEE application server, such as JBoss, Weblogic, WebSphere, and more. We may deploy multiple applications into the same JEE container. In the microservices approach, each microservice will be built as a fat jar embedding all dependencies and run as a standalone Java process:
Microservices may also get their own containers for execution, as shown in the preceding diagram. Containers are portable, independently manageable, and lightweight runtime environments. Container technologies, such as Docker, are an ideal choice for microservices deployments.