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


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" )
public interface EmployeeServiceProxy {
   public EmployeeInfo findById(@PathVariable(value="id") Long id);
   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=[, 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:;    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]
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

Microservices Communication: Service to service

Microservices Communication: Service to service

In the previous microservice tutorial, we have learned How Microservice communicates with the service registry. In this tutorial, we will learn How one microservice communicates with another dependent microservice service via the Service Registry/Eureka Server. This is the second part of Microservice Communication series.

Let see the sequence How One Microservice calls another Microservice using Eureka server.

Registering Service: All Microservices should be registered into Service registry with a Unique name {service-id}, So it can be identified please note that it is an important step as one of the main benefits of Microservice is autoscaling so we can’t rely on Hostname/Ip address so Unique name is important in distributed environment.

Fetching Registry: Before calling the downstream/dependent service Caller service fetch the registry from Eureka server, Registry contains all the active services register into service registry.

Find the Downstream service: Now using the unique service Id caller service get the instance of downstream service.

Resolve Underlying IP address : Please note the Iniques service id act as a Key in service registry but network does not know about it network expects Hostname to call the desired Rest Endpoint on the dependent service like(localhost:8080/employee/{id} or employee.cognizant,com/2 etc) so it is required to resolve the actual hostname of the dependent service Eureka API provides a method for that we just invoke that method to get the Ip address, For a distributed system it is the public IP of Load balancer.

Call the Rest Endpoint: After resolving the IP address using Spring Resttemplate we call the actual Rest endpoint and got the data.

 microservices communication

Coding Time :

For this example we need Three Microservices Project

  1. Employee Search Service : Which we created earlier for searching Employee information.
  2. Eureka Server : Also ,we created this earlier we will reuse that same application
  3. Employee Dashboard Service : We will create this module and call the Employee Search service via Eureka server to get Employee information.

Step 1:Create a service called EmployeeSearchSearch.java  where I  insert some employee using static block and using Java 8 Stream after that I add two methods findById and findAll to display Employee information accordingly.

package com.example.EmployeeSearchService.service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.stereotype.Service;

import com.example.EmployeeSearchService.domain.model.Employee;

public class EmployeeSearchService {

   private static Map<Long, Employee> EmployeeRepsitory = null;

   static {

      Stream<String> employeeStream = Stream.of("1,Shamik  Mitra,Java,Architect", "2,Samir  Mitra,C++,Manager",
              "3,Swastika  Mitra,AI,Sr.Architect");

      EmployeeRepsitory = employeeStream.map(employeeStr -> {
          String[] info = employeeStr.split(",");
          return createEmployee(new Long(info[0]), info[1], info[2], info[3]);
      }).collect(Collectors.toMap(Employee::getEmployeeId, emp -> emp));


   private static Employee createEmployee(Long id, String name, String practiceArea, String designation) {
      Employee emp = new Employee();
      return emp;

   public Employee findById(Long id) {
      return EmployeeRepsitory.get(id);

   public Collection<Employee> findAll() {
      return EmployeeRepsitory.values();


Step 2: Now add a new controller called EmployeeSearchController expose two endpoints by which other services can call findById and findAll method. findById takes Employee Id and returns the Employee Domain Object.

package com.example.EmployeeSearchService.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.EmployeeSearchService.domain.model.Employee;
import com.example.EmployeeSearchService.service.EmployeeSearchService;

public class EmployeeSearchController {
   EmployeeSearchService employeeSearchService;

   public Employee findById(@PathVariable Long id){
      return employeeSearchService.findById(id);
   public Collection<Employee> findAll(){
      return employeeSearchService.findAll();

Employee Domain Object

package com.example.EmployeeSearchService.domain.model;

public class Employee {
   private Long employeeId;
   private String name;
   private String practiceArea;
   private String designation;
   private String companyInfo;
   public Long getEmployeeId() {
      return employeeId;
   public void setEmployeeId(Long employeeId) {
      this.employeeId = employeeId;
   public String getName() {
      return name;
   public void setName(String name) {
      this.name = name;
   public String getPracticeArea() {
      return practiceArea;
   public void setPracticeArea(String practiceArea) {
      this.practiceArea = practiceArea;
   public String getDesignation() {
      return designation;
   public void setDesignation(String designation) {
      this.designation = designation;
   public String getCompanyInfo() {
      return companyInfo;
   public void setCompanyInfo(String companyInfo) {
      this.companyInfo = companyInfo;
   public String toString() {
      return "Employee [employeeId=" + employeeId + ", name=" + name + ", practiceArea=" + practiceArea
              + ", designation=" + designation + ", companyInfo=" + companyInfo + "]";


Step 3: Create an EmployeeDashBoard application by downloading the template for this, I choose following modules actuator, config client, web, Jersey, EurekaClient.

Now put @EnableDiscoveryClient on top of EmployeeDashBoardApplication class. To treat this module as Eureka Client and add RestTemplate as a Spring Bean.

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.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

public class EmployeeDashBoardServiceApplication {

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

Also, rename the application.properties to bootstrap properties and write the following properties.
security.basic.enable: false   
management.security.enabled: false

Step 4: Now create a Controller called EmployeeInfoController , and call the  Service Registry then find the EmployeeSerchService by passing the service-id of the Employee Service see (EmpoyeeService-> bootstrap.properties)
Now call IpAdress method to resolve Ip address and call the dependent service using RestTemplate.

package com.example.EmployeeDashBoardService.controller;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.example.EmployeeDashBoardService.domain.model.EmployeeInfo;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;

public class EmployeeInfoController {
    private RestTemplate restTemplate;
    private EurekaClient eurekaClient;
    private String employeeSearchServiceId;

   public EmployeeInfo findme(@PathVariable Long myself){
      Application application = eurekaClient.getApplication(employeeSearchServiceId);
       InstanceInfo instanceInfo = application.getInstances().get(0);
       String url = "http://"+instanceInfo.getIPAddr()+ ":"+instanceInfo.getPort()+"/"+"employee/find/"+myself;
       System.out.println("URL" + url);
       EmployeeInfo emp = restTemplate.getForObject(url, EmployeeInfo.class);
       System.out.println("RESPONSE " + emp);
       return emp;
   public  Collection<EmployeeInfo> findPeers(){
      Application application = eurekaClient.getApplication(employeeSearchServiceId);
       InstanceInfo instanceInfo = application.getInstances().get(0);
       String url = "http://"+instanceInfo.getIPAddr()+ ":"+instanceInfo.getPort()+"/"+"employee/findall";
       System.out.println("URL" + url);
       Collection<EmployeeInfo> list= restTemplate.getForObject(url, Collection.class);
        System.out.println("RESPONSE " + list);
       return list;

Then Up the services in following Order

  1. Start config server.
  2. Start Eureka Server.
  3. Start Employee Search Service.
  4. Start Employee DashBoard Service.

When all services are Up-- hit http://localhost:9091 in browswer you will see all services are up and Running

microservice tutorial
Add caption

Then hit the following URL http://localhost:8081/dashboard/2
You will see the Following Output.

{"employeeId":2,"name":"Samir  Mitra","practiceArea":"C++","designation":"Manager","companyInfo":"Cognizant"}