Microservices Tutorial: Ribbon as a Load balancer


In the previous Microservice tutorial , we have learned How to communicate with other Microservice using Feign as a REST client and Eureka server as a Service discovery.

In all cases, We consider only one instance of a Microservice-- which calls another instance of dependent Microservice(EmployeeDasBoard service call to EmployeeSearch service).
This is good for demo purpose or when you are practicing How to develop Microservice.
In production, Certainly it is not the case-- we break Monolith application to Microservice applications because we can scale each service based on the payload. So Single instance of a service is unimaginable in production-- so what we generally do is, using a load balancer which balancing the payload among multiple instances of a service.


Before digging into Ribbon the Client side Load Balancer for Microservice architecture, Let discuss How our old fashioned Java EE services AKA Monolith maintains Load balancing.


Server Side Load Balancing :  In java EE architecture we deploy our war/ear files into multiple application servers, then we create a pool of server and put a load balancer(Netscaler)in front of it. Which has a public IP. The client makes a request using that public IP and Netscaler decides in which internal application server it forwards the request by Round robin or Sticky session algorithm. We call it Server side load balancing.

server side Load Balancing
Server Side Load Balancing


Problem : The problem of server side load balancing is if one or more servers stop responding we have to manually remove those servers from Load balancer by updating IP table of the Load balancer.
Another problem is we have to implement failover policy to provide the client a seamless experience.
But Microservice not using the server side load balancing. It uses client side Load balancing.


Client side Load Balancing : To understand Client Side Load balancing let's recap the Microservice architecture.  We generally create a Service discovery like Eureka or Consul where each service instance register when bootstrapped. Eureka server maintains a Service registry, it maintains all the instances of the service as Key/value map.Where {service id} of your Microservice serves as Key and instance serve as Value. Now if one Microservice wants to communicate other Microservice it generally looks up the service registry using DiscoveryClient and Eureka server returns all the instances of the calling Microservices to the caller service. Now it is Caller service headache which instance it calls. Here Client side Load balancing stepped in. Client side Load Balancer maintains Algorithm like Round robin or Zone specific by which it can invoke instances of calling services. The advantage is as Service registry always updated itself if one instance goes down it removes it from its registry so When Client side Load balancer talks to Eureka server it always updates itself so there is no manual intervention unlike server side load balancing to remove an Instance.

Another Advantage is as Load balancer is in client side you can control its Load balancing algorithm programmatically.

Ribbon provides this facility so we will use Ribbon for Client side Load balancing.



client side load balancing
Client Side Load Balancing






Coding Time

We will configure Ribbon in Our EmployeeDashBoradService which will communicate with Eureka to fetch EmployeeSearchservice instances.

Step 1: To enable Ribbon in EmployeeDashBoard we have to add the following dependency in pom.xml

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>

Step 2:  Now we have to Enable Ribbon so it can Load balance the EmployeeSerach Application so for that we need to put @RibbonClient(name="EmployeeSearch") on top of the EmployeeServiceProxy interface. By doing this we instruct Spring boot to communicate Eureka server and get the list of instances for service id EmployeeSerach. Please note that this is the {service-id} for the Employeeserach application.
package com.example.EmployeeDashBoardService.controller;

import java.util.Collection;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.EmployeeDashBoardService.domain.model.EmployeeInfo;



@FeignClient(name="EmployeeSearch" )
@RibbonClient(name="EmployeeSearch")
public interface EmployeeServiceProxy {
   
   @RequestMapping("/employee/find/{id}")
   public EmployeeInfo findById(@PathVariable(value="id") Long id);
   
   @RequestMapping("/employee/findall")
   public Collection<EmployeeInfo> findAll();

}


Our Ribbon Client is ready now.

Testing time:

Start Configserver and Eureka server first.
Then Start EmployeeService it will up on port 8080 as we mentioned in bootstrap.preoperties.
Now Run another instance but this time starts with -Dserver.port=8082 so another instance up on 8082 port.

After that run the EmployeeDashBoard service.

Now check the Eureka server GUI it will look like following





Now if you hit the following URL


You can see the following response

{
   "employeeId": 1,
   "name": "Shamik  Mitra",
   "practiceArea": "Java",
   "designation": "Architect",
   "companyInfo": "Cognizant"
}

Now open the EmployeedashBorad Console you can see following lines are printed in console

DynamicServerListLoadBalancer for client EmployeeSearch initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=EmployeeSearch,current list of Servers=[192.168.0.103:8080, localhost:8082],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;    Instance count:2;    Active connections count: 0;    Circuit breaker tripped count: 0;    Active connections per server: 0.0;]
},Server stats: [[Server:localhost:8082;    Zone:defaultZone;    Total Requests:0;    Successive connection failure:0;    Total blackout seconds:0;    Last connection made:Thu Jan 01 05:30:00 IST 1970;    First connection made: Thu Jan 01 05:30:00 IST 1970;    Active Connections:0;    total failure count in last (1000) msecs:0;    average resp time:0.0;    90 percentile resp time:0.0;    95 percentile resp time:0.0;    min resp time:0.0;    max resp time:0.0;    stddev resp time:0.0]
, [Server:192.168.0.103:8080;    Zone:defaultZone;    Total Requests:0;    Successive connection failure:0;    Total blackout seconds:0;    Last connection made:Thu Jan 01 05:30:00 IST 1970;    First connection made: Thu Jan 01 05:30:00 IST 1970;    Active Connections:0;    total failure count in last (1000) msecs:0;    average resp time:0.0;    90 percentile resp time:0.0;    95 percentile resp time:0.0;    min resp time:0.0;    max resp time:0.0;    stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@a1df28c
2017-08-04 22:56:47.180  INFO 3293 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty  : Flipping property: EmployeeSearch.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647



Is Data Abstraction and Encapsulation a fancy term of Information Hiding?

I have seen many developer/Architect use the term interchangeably and has the reason for it but yes there are differences-- a huge difference in terms of hiding information. I try to explain it in a Simple way.
Let’s start by the definition.
Encapsulation: binds data and behaviors together in a Single unit and behaviors acts on the data.
Abstraction: Hiding the implementation details and expose the functionality to the world.

According to both definition, both try to hide data from rest of the world and expose some behaviors/method so other System/API can use it.

At this point Both are same so If someone uses those term Interchangeably they are correct.
But hold why then Two fancy concepts are side by side in OOP why they are not merged into a one and called it “Information hiding

To understand the same take a look Suppose you have to implement a car.
So when you rotate the steering lots of thing happening inside and eventually car is moving to the direction you rotate the steering.
Now let explain the Action in details
Input: Steering rotation direction.
Output: car moves in the Direction steering rotated.
but what is happening inside is a black box to the user—That is called Abstraction
So technically it says What to abstract from User?
Abstraction is a functionality which helps the developer to identify what is the functionality that should be abstracted and exposed as a function/method which takes User input and returns desired result what User wants.
In a car Steering functionality, Braking functionality, Auto parking --these are the functionalities has to be abstracted from User— User less interested How it works but what they interested is What should I do(Input) and What will be the Outcome. So according to me Abstraction is

Abstraction:  By Abstraction, developers identify the functions what should be published in API and what input it takes and What Output it returns.

So, another point of view is, Abstraction helps us to the generalization of a functionality-- So When you design a function’s input or output you should be very careful about the data type you used-- It should be supported all possible combination on which function can be applied.


Now come to Encapsulation It tells about How to achieve the functionality-- which has been identified by Abstraction.

So it tells us about the packaging the data and behaviors.
Take the same example use steering to move the car.
Encapsulation: identifies the different parts associate to move the car using user instruction like steering, Wheel, Engine.Petrol . Also, it identifies the algorithm/behaviors which will be applied to these data(wheel, steering, engine, petrol) to move the car, and help to binds or packaging as one single unit. In my perspective Encapsulation definition is.


Encapsulation:Encapsulation Helps to understand what are the data and functions, that should be bundled as a Single Unit so User can act on them without knowing internal details and get the job done.
Information Hiding
Explanation of the figure: When you design an API/Class always there is two perspective one is Developers View and one is API User view. From Developers View Abstraction is to identify the features to be provided and Encapsulation is the process to communicate with internals things and provide the functionality. So it makes sense to have two distinct terminology Abstraction and Encapsulation.

But for User of the API/Class, It is like what functionality is exposed and what is the input and what will be the output so functionality an API provides nothing but Opaque things to them they provide input and got Output --API or Class is a barrier or Facade for them So for them it is just an Information hiding so Abstraction and Encapsulation has no meaning for them. It can be used alternatively to mention information hiding.

Conclusion :  Abstraction and Encapsulation both are used for hiding information context but their purpose is different.  Abstraction helps to understand the functionality User interested for and providing the same to the user as a black box. Encapsulation is about the gathers the required data and algorithm to solve the purpose for the user and tied them in a single Unit so the user of the API  doesn't have to collects the data and apply the algorithm by itself to get the job done.

Microservices Communication: Feign as Rest Client


In the previous microservice tutorial, we have learned How Microservice communicates with each other using RestTemplate. In this tutorial, we will learn How one microservice communicates with Other via Feign Client . This is the third part of Microservice Communication series.



What is a Feign Client?

Netflix provides Feign as an abstraction over Rest-based calls, by which Microservice can communicate with each other, But developers don’t have to bother about Rest internal details.

Why we use Feign Client?

In my previous tutorial, When EmployeeDashBoard service communicate with EmployeeService, Programmatically we had constructed the URL of dependent Microservice-- then call the service Using RestTemplate so we need to aware about the RestTemplate API to communicate with other microservice, which is certainly not part of our Business logic-- So question is Why should developer has  to know details of  Rest- API, Microservice developers only concentrate on Business logic so Spring Address this issues and comes with Feign Client which works on  declarative principle . We have to create an Interface/contract then Spring creates the original implementation on the fly so Rest-based service call is abstracted from developers. Not only that if you want to customize the call like Encode your request or decode the response in a Custom Object, Logging -- you can do it by Feign in a declarative way.  Feign a client is an important tool for Microservice developer to communicate with other Microservices via Rest API.


spring boot microservices--FeignClient






Coding Time:


Here we will alter our EmployeeDashborad Service to make it Feign enable;
Step 1 : we will add feign dependency into EmployeeDashBoard Service.

<dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>

Step 2: Now, We have to create an Interface where we declare the services which we wanted to call, Please note that the Service Request mapping is same as  EmployeeSerach Service Rest URL. Feign will call this URL when we call EmployeeDashBorad service.

Feign dynamically generate the Implementation of the interface which  we created , So Feign has to know which service to call before hand that's why we need to give a name of the interface which is the {Service-Id} of Employee Service, Now Feign contact to Eureka server with this Service Id and resolve the actual Ip/Host name of the Employee Service and call the URL provided in Request Mapping.
NB : when using @PathVariable for Feign Client use value property always unless it will give you the error java.lang.IllegalStateException: PathVariable annotation was empty on param 0


package com.example.EmployeeDashBoardService.controller;

import java.util.Collection;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.EmployeeDashBoardService.domain.model.EmployeeInfo;



@FeignClient(name="EmployeeSearch" )//Service Id of EmployeeSerach service
public interface EmployeeServiceProxy {
   
   @RequestMapping("/employee/find/{id}")
   public EmployeeInfo findById(@PathVariable(value="id") Long id);
   
   @RequestMapping("/employee/findall")
   public Collection<EmployeeInfo> findAll();

}

Step 3 : Now we will create a FeignEmployeeInfoController where we autowired our Interface so in runtime Spring can Inject actual implementation, then we call that implementation to call EmployeeService Rest API.

package com.example.EmployeeDashBoardService.controller;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.EmployeeDashBoardService.domain.model.EmployeeInfo;

@RefreshScope
@RestController
public class FeignEmployeeInfoController {
   
   @Autowired
   EmployeeServiceProxy proxyService;
   
   @RequestMapping("/dashboard/feign/{myself}")
   public EmployeeInfo findme(@PathVariable Long myself){
      return proxyService.findById(myself);
     
   }
   
   @RequestMapping("/dashboard/feign/peers")
   public  Collection<EmployeeInfo> findPeers(){
        return proxyService.findAll();
   }

}


Step 4: At Last , we need to tell our project that we will use Feign client so please scan it’s annotation. For this , we need to add @EnableFeignClients annotation on top of
EmployeeDashBoardServiceApplication

package com.example.EmployeeDashBoardService;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class EmployeeDashBoardServiceApplication {

   public static void main(String[] args) {
      SpringApplication.run(EmployeeDashBoardServiceApplication.class, args);
   }
   
   @Bean
   public RestTemplate restTemplate(RestTemplateBuilder builder) {
      return builder.build();
   }
}


Now we are all set for use Feign client.

Testing Time:

Start the following Microservices in order.

  1. EmployeeConfigServer
  2. EmployeeEurekaServer
  3. EmpolyeeSerachService.
  4. EmployeeDashBoardService


Now hit the url  http://localhost:8081/dashboard/feign/peers in browser

You will see following output

[
   {
      "employeeId": 1,
      "name": "Shamik  Mitra",
      "practiceArea": "Java",
      "designation": "Architect",
      "companyInfo": "Cognizant"
   },
   {
      "employeeId": 2,
      "name": "Samir  Mitra",
      "practiceArea": "C++",
      "designation": "Manager",
      "companyInfo": "Cognizant"
   },
   {
      "employeeId": 3,
      "name": "Swastika  Mitra",
      "practiceArea": "AI",
      "designation": "Sr.Architect",
      "companyInfo": "Cognizant"
   }
]