Microservices Communication: Zuul API Gateway

In the previous Microservice tutorial, we have learned How Microservices handling Client side Load balancing.

Here, we will discuss Zuul proxy.

What is a Zuul Proxy ?

The Crux of Microservices pattern is to create an Independent service which can be scaled, deployed independently. So in a complex Business Domain-- more than  50-100 Microservices is very common. Let's Imagine a System where we have fifty Microservices now we have to implement a UI which is kind of a dashboard -- So it calls Multiple services to fetch the important information and show that in UI.

From UI developer perspective --  to collect information from fifty underlying Microservices it has to call fifty Rest API as each Microservice exposes a Rest API for Communication. So the client has to know the details of all Rest API and URL pattern /port to call them. Certainly, it is not sound like a good design. It is kind of a breaching of  Encapsulation, UI has to know all Microservices server/port details to query the services.

Moreover think about the Common aspects of a Web programming like CORS, Authentication, Security, Monitoring in terms of this design -- Each Microservice team has to develop all these aspects into its own service so same code has been replicated over fifty Microservices, Change in the Authentication requirements or CORS policy rippled overall services. It is against of DRY principle. So This type of design is very error prone and rigid. To make it robust It has to be changed in such way so that we have only one entry point where all common aspects code are written and client communicates with that common service. Here the Zuul(The Gatekeeper/demigod ) Concept pops up.


microservices architecture-Zuul




Edge Service: Zuul acts as an API gateway or Edge service. It receives all the request comes from UI and then delegates the request to internal Microservices. So we have to create a brand new Microservice which is Zuul enabled and this service sits on top of all other Microservices. It acts as an Edge service or Client facing service. Its Service API should be exposed to client/UI, Client calls this service as a proxy for Internal Microservice then this service delegates the request to appropriate service.

The advantage of this type of design is common aspects like CORS, Authentication, Security can be put into a centralized service, so all common aspects will be applied on each request, and if any changes occur in the future we just have to update the business logic of this Edge Service.


Also, we can implement any Routing rules or any Filter implementation says we want to append a special tag into the request header before it reaches to internal Microservices we can do it in the Edge service.

As Edge service itself is a Microservice so it can be independently scalable, deployable. So we can perform some load testing also.





edge services








Coding Time:

Create a project using http://start.spring.io/ named it as EmployeeZuluService select Zuul and Eureka Discovery module as Edge service itself a Eureka client.

The pom.xml  will look like following


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.example</groupId>
   <artifactId>EmployeeZuulService</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>EmployeeZuulService</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.6.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
      <spring-cloud.version>Dalston.SR2</spring-cloud.version>
   </properties>

   <dependencies>
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-eureka</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-zuul</artifactId>
      </dependency>

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
      </dependency>
   </dependencies>

   <dependencyManagement>
      <dependencies>
          <dependency>
              <groupId>org.springframework.cloud</groupId>
              <artifactId>spring-cloud-dependencies</artifactId>
              <version>${spring-cloud.version}</version>
              <type>pom</type>
              <scope>import</scope>
          </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
          <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
      </plugins>
   </build>


</project>



Next, rename the application.properties to bootstrap.properties and write down the following configuration there.




spring.application.name=EmployeeAPIGateway
eureka.client.serviceUrl.defaultZone:http://localhost:9091/eureka
server.port=8084
security.basic.enable: false   
management.security.enabled: false
zuul.routes.employeeUI.serviceId=EmployeeDashBoard
zuul.host.socket-timeout-millis=30000

As this is a Microservice so its need to be registered in Eureka server so it can be aware of other services.

Also, this service runs on port 8084.

Pay attention to lats two properties
zuul.routes.employeeUI.serviceId=EmployeeDashBoard

By this, we say if any request comes to API gateway in form of

/employeeUI it will redirect to EmployeeDashBoard Microservice

So if you hit the following URL

It will redirect to


Note that UI developer only aware of the Gateway service port, it is Gateway service responsibility to route the service to appropriate Microservice.

NB: Zuul can be implemented without Eureka server, In that case, you have to provide the exact URL of the service where it will be redirected.



zuul.host.socket-timeout-millis=30000 -- by this we instruct Spring boot to wait response for 30000 ms unless Zuuls internal Hystrix timeout will kickoff and showing you the error.

Now add @EnableZuulproxy and @EnableDiscoveryClient on top of  EmployeeZuulServiceApplication class

package com.example.EmployeeZuulService;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class EmployeeZuulServiceApplication {

   public static void main(String[] args) {
      SpringApplication.run(EmployeeZuulServiceApplication.class, args);
   }
}



Our API gateway service is ready.

Noe starts the config server, Eureka server, EmployeeSearchService, EmployeeDasboradService and, EmployeeZuulService respectively.

If you hit the following URL


You will see the following output

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

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