1. Microservices Interview Question

 1. What is Difference between Monolithic and Microservices Architecture ? 

However, the Monolithic word derived from the monolith, which normally means an object made from a single large piece of material. 

1. Monolithic Architecture : 

  • In monolithic architecture where all components are combine in single Large Application.
  • The Monolithic arch are build as single unit means all the layer like presentation layer , service layer , Data Access Layer all are those are include in the that single Application and It has single logical executable.

Real time Example :  as like Four Brother  of single family living a Single House. 


  • There are several advantages of Monolithic Architecture

1. as like it Simple to Develop ( it dividing into multiple layer and that layers just simplifies the development process).

2. Testing is easy in Monolithic Arc.

3. Simple to scale . (We can perform horizontal scaling by running multiple instances behind a load balancer)


  • There are Several Dis Advantages of Monolithic Architecture.

- If we want to make small changes in our application then for that changes we have need to re-build and re-Deploy our entire application.

- And we Want to add any new Feature or Integration then its complex to add that feature in Monolithic Architecture.

- As like while creating a application when we increase the number of module in application then size will increase of our application then that situation our code become a complex and then its difficult to maintain.

            Ex : FlipKart   1. User 2. Cart , 3. Order , 4. Payment 5. Shipment


we use REST API the for Communication between Monolithic Architecture.  


2. Microservices

  • In microservices where all parts large application  divided into small parts.
  • In simple words, Microservice is all about distributing or breaking a large application into small pieces(services).
  • We use Microservice Architecture in our application  where we use to create multiple independent module (services) for the perform independent functionality , as like standalone task.
  • so then we make any changes in any module(services) then it does not effect on any other module .which is Opposite to or not similar to  Monolithic Architecture .   
  • and all module communicate with each using API.   

- Real time Example Microservices :  

1. as like Four Brother of single family they four living a Different cities they communicate with each other using mobile call.

  2. Ex: if IPL is one application & all difference team is service.

  • Advantages of Microservices 

- Accelerate scalability

- Improve fault isolation

- Enhance team productivity

- Quicker deployment time

- Increase cost-efficiency



What is the main advantage of using microservices in Java applications?

- The primary advantage of using microservices is improved scalability, maintainability, and flexibility. Microservices allow us to develop, deploy, and scale each component independently, making it easier to adapt to changing requirements and handle high loads.

        - Deployment

        - Decentralization

        - Loosely Couple

        - Security

        - Scalable 



- How can I communicate between microservices in a Java-based microservices architecture?

- We can use various communication methods, such as HTTP/REST APIs, messaging systems (e.g., Apache Kafka or RabbitMQ), or gRPC. The choice depends on our specific use case and requirements.


2. Can you tell me what are the main components of microservices and what is the use of API Gateway ?

  • In case of microservices architecture so there are for each business related functionality there is one micro project which is either in spring boot or any other language and there are multiple projects running on different port on the same machine or different machine .
  • so if you want to access the rest API all the application then we need URL and port in short we need address of each microservice but client cannot have address of each microservices so generally there is API Gateway so client only knows the address of API Gateway
  • and API gateway knows for this request which microservice to contact so the basic duty of API Gateway is to accept the request from client and then redirect that request to appropriate microservice and then return the response back to the client 
  • so there are various other functionalities which API Gateway handles API Gateway also handle authentication and authorization , API Gateway also handle rate limiting so multiple request are coming from one client which is not acceptable then we can add that logic in API Gateway .
  • zuul is common example of API Gateway .


  • Core Component of Microservices 
  • API Gateway :  An entry point for client requests that routes requests to the appropriate microservices, performs authentication and authorization, and handles other tasks such as caching and request-response mapping.
  • Service Discovery :  A service registry that helps services locate and communicate with each other. 
  • Service Orchestration : A layer that coordinates communication and interactions between microservices to ensure that they work together correctly. 
  • Load Balancer : A component that distributes incoming requests to the appropriate service instances. 
  • Service Registry :  A database of all available microservices, their endpoints, and metadata. 
  • Circuit Breaker :  A mechanism that helps prevent cascading failures by interrupting communication between services when one service is not responding. 
  • Service Monitoring : A system that tracks the health and performance of microservices and generates alerts in case of failures or performance degradation. 
  • Configuration Server :  A centralized repository for storing configuration information that is accessible to all microservices.




[ Note : - Reason :  In the case of a Monolithic Application, there we have only one server so we used to remember the server IP and the port but now your monolithic has been split into thousands of applications how’ll be handling that? And for that Spring Cloud is providing us with Service Discovery and Service Registry to handle this problem ].  


3. What is Netflix Eureka Server / Discovery Server .

  • The main purpose of Eureka/Discovery Server is where server can register them in microservices and discover them when require by other Microservices. 
  • We call it Eureka Server or Discovery server.
  • Eureka server have all the information of registered microservices  as like (port, IP address) which microservices running on client application. 
  • So Implement Eureka server we have add to dependency  "spring-cloud-starter-eureka-server " and we have to @EnableEurekaServer annotation for Eureka server 
  • Example :  Attendance Sheet in College where all so teacher can call  students which names register in the sheet.


4. What is Discovery Service and Service Registry 

- So in Microservice there multiple services running in our application and when one Service want to communicate with other so there is medium where all service have to register themselves. and that medium is Discovery Service. and service registry store the information about IP address and port. and where service registry acts like central where service register their network locations, capabilities, and metadata.


Ex : example like WhatsApp , Instagram like registry service and multiple user communicate with each is like discovery service. 

- There Load Balancer  also included Where The  Load Balancer job is to do load balancing while the Service Discovery job is to do discovering service info. When we build Microservices and call other microservices, we need service discovery to find the hosts and IP info and if multiple hosts are available then the load balancer helps to pick one and make a call in a load-balanced way.

- In short Load Balance pick one host if there are multiple host available.  


- Types of Service Discovery

There are two types of Service Discovery

1. Client-Side Service Discovery :Example : Netflix Eureka, Zookeeper, Consul

2. Server-Side Service Discovery :Example : NGNIX, AWS ELB




5. How to enable Load Balancer?

- for  enable Load Balance we use Feign Client & Eureka , So we have add dependency of feign client  " spring-cloud-starter-openfeign" .


6. What is Microservices Intra-communication?

-  A published microservice communicates with the other microservice with the help of Eureka Server itself. 

-  For Intra Communication with other microservices we user eureka Server , And We use one client details of a microservices from Eureka Server. 

1. DiscoveryClient (Legacy client)

2. LoadBalancerClient (new client) 

3. FeignClient/Open Feign (Abstract client)



7. What is API Gateway?

API Gateway is a Single Entry point and exist of all microservices in the application . In term of 

Example :  It like Main Gate of Our College everyone enter through that Gate.

  • API Gateway It also one Type of Microservice that call to other microservices using Eureka Server. 
  • So API Gateway  generate class (Proxy)  to accept incoming request from clients, and perform various operations such as routing, authorazation, authentication, and rate limiting , and then forward those to appropriate backend services.
  • API Gateway helps in implementing Security, applying filters, SSO(Single Sing On), routing etc.
  • To implement API Gateway we can use Zuul Proxy server which handle all request and does dynamic routing of microservices. 
  • To Implement API Gateway we can use Zuul proxy server and Other newer one is Spring Cloud Gateway.

    

        Example : assume village is gateway village has " SARPANCH " is like proxy then sarpanch will handle all things like contruct roads, as short development of village  


- Zuul Proxy Server

- order to implement API Gateway, we can use Zuul Proxy Server that handles all the requests and does the dynamic routing of microservices. Dynamic routing is nothing but choosing one microservice instance and make HTTP call based on the load. We also sometimes call it as Zuul Server or Edge Server. We add the @EnableZuulProxy annotation on our main application class to make our Spring Boot application act as a Zuul Proxy server. dependency "spring-cloud-starter-zuul" .

-  Note : Newer versions of Spring Boot suggests us to use Spring Cloud Gateway in place of Zuul.




Feign Client 

- The Feign is a declarative Http web client developed by Netflix.

- If you want to use Feign, create an interface and annotate it.


{ Note : Declarative REST Client means to specify the client specification as an Interface and spring boot will take care of the implementation. }

8. What is Feign or Open Feign and Where do we use it?

- Feign, often referred to as “OpenFeign,” is a Java-based  declarative REST Client. 

- OpenFeign is used in microservices and cloud-native applications to simplify communication between different services. 

- It is a part of the Spring Cloud ecosystem and designed to work smoothly with other Spring Cloud components to create microservices-based applications. 

- In simple words, it simplifies the process of writing web service clients.

- In order to use Feign, create an interface and apply @FeignClient annotation on it. 

- Feign internally generates a Proxy class at runtime using Dynamic Proxy Pattern. It actually gets Application name (Service Instance) from Eureka and supports Making HTTP calls. Generally, we use two annotations for this concept, they are:

1. @EnableFeignClients :  To apply at starter class

2. @FeignClient(name=”ApplicationName”) : To define an interface for a Consumer


- In term Producer-Consumer model the feign client is better choice instead of RestTemplate in order to minimize our coding effort.

- Apart from consuming REST services in an easy way, FeignClient/OpenFeign when combined with Eureka also provides us an easy load balancing.



9.  Why we use Feign Client in Microservices ?
- Feign simplifies the process of making API calls in a microservices architecture.  there are multiple reasons to use Feign Client in Microservices:
1) Simplifies API calls: Feign allows us to define our API interface using annotations, which makes it easier to create API clients and eliminates a lot of boilerplate code.
2) Declarative programming: Feign uses declarative programming, which means that we only need to specify what we want to do, not how to do it. This makes it easier to read and maintain our code.
3) Load balancing and service discovery: Feign integrates well with other tools like Netflix Eureka and Consul, which offer service discovery and load balancing abilities. This makes it easier to call services that are running on different instances or nodes.
4) Inter-service communication: In a microservices architecture, services need to communicate with each other frequently. Feign makes it easier to call other services by creating a client for each service and using them to make HTTP requests.



10. Spring Cloud Gateway ( It similar like AOP)
- Spring Cloud Gateway is a simple, yet an effective way to route to APIs. It also offers implementation of various cross cutting concerns such as Security, Logging, Monitoring/metrics etc. It is built on top of Spring Webflux (A reactive programming approach), We need to add the dependency as " spring-cloud-starter-gateway " in order to get features of Spring Cloud Gateway.

- Some important features of the Spring Cloud Gateway are:
1) Match routes on any request attribute
2) Define Predicates & Filters
3) Integrates with Spring Cloud Discovery Client (Load Balancing)
4) Path Rewritting


11. Producer-Consumer Model / technique .

- When two web applications communicate with each other for data exchange, they work on Producer-Consumer technique. An application who produces data is known as a Producer/Provider application. Similarly the one who consumes data is known as Consumer application. 

- REST API for Producer application whereas RestTemplate for Consumer application. With Microservices based application also, two Microservices communicate with each other and follow the Producer-Consumer model. 



What is Fault Tolerance in Microservices?

In a context of Microservices, Fault Tolerance is a technique of tolerating a fault. A Microservice that tolerates the fault is known as Fault Tolerant. Moreover, a Microservice should be a fault tolerant in such a way that the entire application runs smoothly.


12. What is Fault Tolerance in Microservices?

- When we work on a microservices architecture based application, there are multiple small microservices, and they all communicate with each other. Suppose that a microservice goes down at any point of time, all the other microservices that are directly or indirectly dependent on it, will go down as well. Hence, we should have a solution in case a microservice fails. This aspect of a microservice is called fault tolerance.

- In order to implement complete Fault Tolerance, even including circuit breaker, we use Resilience4j API. It has multiple separate modules such as Rate Limiter, Time Limiter, Bulkhead, Circuit Breaker, Retry etc. 

-  we require  Resilience4j dependencies to implement. 



13. What is a Circuit Breaker?

  • Circuit Breaker is a design pattern used in microservices architecture where different services interacting with each other over a network and circuit breaker protects them from cascading failures to enhance the resiliency and fault tolerance of a distributed system. 
  • Circuit breaker prevent to system from cascading failure and fault tolerance.
  • In simple terms, a Circuit Breaker is a protective and safety mechanism that prevents your application from continuously making requests to a service that has problems. 
  • The circuit breaker has three states:
  1. Closed: In this state, the circuit breaker allows normal service communication, and requests go through to the service.
  2. Open : When the number of failures reaches a threshold, the circuit breaker switches to the open state, preventing requests from reaching the service and providing a fallback response. 
  3. Half Open : Once the timeout or reset interval passes, the circuit breaker goes to the “Half-Open” state.
  • - There are several tools and frameworks implementing the circuit breaker pattern. Here are some popular options:

- 1. Netflix Hystrix (हि  : hi · struhks ) is an open-source Java library that provides an implementation of the circuit breaker pattern to handle faults tolerance and latency in distributed systems and microservices architectures.

- 2. Resilience4j: Resilience4j is a lightweight, easy-to-use library, which offers a powerful circuit breaker implementation inspired by Netflix Hystrix but designed with functional programming approach.

- 3.Istio: Istio is a service mesh platform that helps you manage traffic between microservices. 

- 4.Sentinel: It is an open-source library that provides monitoring of services and controls the traffic.


 Characteristics of Circuit Breaker Pattern

- Fault Tolerance: Enhances fault tolerance by isolating and managing failures in individual services.

- Monitoring: Continuously monitors interactions between services to detect issues in real time.

- Failure Isolation: Temporarily stops requests to failing services, preventing cascading failures and minimizing disruptions.

- Fallback Mechanism: Provides fallback responses or error messages to clients during service failures, ensuring graceful degradation.

- Automatic Recovery: Automatically transitions back to normal operation when the failing service recovers, improving system reliability




14. What Rate Limiter ? 

        - We use rate limiter to provide security and increase the performance.

- This Functionality allows limiting access to some service .

- Rate Limiter make services highly available by limiting the number of calls we could process in specific windows.

- Rate Limiter the restrict the request on particular level . Where we set time Limit for request .

- Types ; 1. RPS : Rate Per Second , 2. RPM : Rate Per Minutes , 3. RPH : Rate Per Hour



    
[   What is a configuration? :  A configuration is anything that varies between multiple environments, like the DEV, TEST, UAT, and PROD environments. This includes your database credentials, external API URLs, and app-specific configurations.  ]



15. What is Spring Cloud Config Server?  
  • Spring Boot Config Server is a powerful tool for managing configuration properties across a large number of microservices.
  • Config Server has a central place that  manage all your application configurations across multiple environments.
  • A centralized repository for storing configuration information that is accessible for the all available microservices.
  • Spring Boot Config Server is use to manage configuration properties for microservices.
  • There are Two types of Config Server as External Config Server and Native Config Server. 
  1. External Config Server: We can implement External Config Server by using GitHub, GitLab, Bitbucket etc. 
  2. Internal Config Server: We can implement Native Config Server just by using local drives of our system which is appropriate only for development environment. 
   Config Clients  : Spring Cloud Config Clients are the microservices who stores their common configurations on Spring Cloud Config Server.
   
Example : college Head Department( config server) where the all department are come together . 



[ Note : Sleuth and Zipkin use for distributed Tracing and Logging Microservices . ]

 16. Where we Use Sleuth and Zipkin ?
- Spring Cloud Sleuth, combined with Zipkin, allows to us perform/implement  distributed tracing for Spring applications. Zipkin is a distributed tracking system originally developed by Twitter , Zipkin visualizes trace data between and within services. 
  1. Sleuth
- Sleuth provides unique IDs for request flows. The developer uses this ID to find the execution flow of a request. 
- There are two types of IDs : Trace ID and Span ID. 
1. Trace ID is a unique Id is for a complete flow (from Request till Response). Using this ID, developer can find out logs of all microservices involved in the flow. 
2. Span Id is a unique ID for one microservice flow. Using this ID, developer can find out log messages for a particular microservice.

2. Zipkin
- Zipkin works in a client server model. In every microservice, we should also add this dependency along with Sleuth. It contains Sampler (Collect data from microservice using Sleuth and provide to Zipkin Server). There must be only one centralized Zipkin Server that collects all data from Zipkin Client and displays it as a UI. Now, Developer should make a request and goto Zipkin Server to find Trace ID, Span ID and flow as well. Then the developer should open Log files to see Log lines related to current Trace Id.
-  In short Zipkin is use to collect data from client and display it as UI.



17. what is ELK  ?
    - ELK Stack (Elasticsearch, Logstash, Kibana) is one of the most popular tools to monitor our application via log analysis.


18. How are Microservices Flexible with Spring Cloud?
- Spring Cloud help developers with service configurations, service discovery, circuit-breaking, load-balancing, distributed tracing & logging, and monitoring. 



19. What is Spring Boot Admin Dashboard?
  • Spring Boot Admin is a web application that manages and monitors multiple Spring boot applications (microservices in our case) and shows the results in the form of a single dashboard. 
  • Generally, microservices developers use it for monitoring of webservices. If we add Spring Actuator to the Spring Boot applications, we can get multiple endpoints to monitor and deal with Spring Boot applications. Each Spring Boot application acts as a client and registers to the Spring Boot Admin Server. 
  • Spring Boot Actuator endpoints provides the magic behind the scene. We apply Actuator to Spring Boot Admin Client Applications and expect the results in Spring Boot Admin Server in the form of a dashboard.
  • We have to add the @EnableAdminServer annotation on our main application class to make our Spring Boot application act as a Spring Boot Admin Server.
  •  we need add "spring-boot-admin-starter-server" Dependency.


What is service-oriented architecture?
  • Service-oriented architecture (SOA) is a software development model that makes services reusable and lets them communicate across different platforms .
  • An SOA service is a self-contained unit of software designed to complete a specific task. Applications use SOA and simple interface standards to access services to form new applications.
  • There are typically four main components in SOA :   1. Service 2. Service Provider 3. Service Consumer 4. Service Registry.

20.  What is the difference between Monolithic, SOA, and Microservices Architecture?

    1. Monolithic

    2. SOA

    3. Microservices


    1. Structure

    1. A single application where all software components are assembled and tightly coupled.

    1. Collection of services and loosely coupled.

    1. Collection of small services and services independently deployable.


    2. Communication


    2. Within the same application, components communicate with each other.

    2. Using some standardized protocols, services communicate with each other.

    2. Through some lightweight protocols, all the services communicate with each other.


    3. Scalability

    3. Scaling is required according to the needs of the entire application.

    3. All services can be scaled independently.

    3. All the services can be scaled independently according to the business requirement.


    4. Development and Deployment

    4. It maintains centralized development and components deployed as a single unit.

    4. It also maintains centralized development and here the services are deployed as monolithic applications.

    4. It maintains decentralized development and services deployed independently.

     

21.  How do Microservices Communicate with each other?
        - In Microservices, multiple services run independently. Services communicate with each other through,
1. HTTP/REST: These are light-weight protocols used for perform communication between two services.
2. Message queues: Message queues such as Kafka or RabbitMQ used to make connection.
3. RPC (Remote Procedure Call) Framework: RPC frameworks such as gRPC uses in services for communication purposes.



22.  What is RestTemplate and How Java Microservices Communicate using RestTemplate?
  • The RestTemplate is a synchronous REST client that performs HTTP requests by using a simple API of template style.
  • This is a synchronous client and it is designed to call the REST services.
  • RestTemplate class plays a very major in Spring Boot Microservices Communication.
  • We can use RestTemplate for Java Microservices Communication by the following approach:
  • Microservices can communicate using RestTemplate.getForObject() method. Syntax of RestTemplate.getForObject() method is given below.

23. What is FeignClient and How Java Microservices Communicate using FeignClient?
  • FeignClient is known as Spring Cloud OpenFeign.
  • It is a declarative REST Client in Spring Boot Web Application. Declarative REST Client means to specify the client specification as an Interface and spring boot will take care of the implementation.
  • With the help of FeignClient, writing web services is very simple.
  • It is mostly used to consume REST API endpoints exposed by third parties or microservices.















Comments

Popular posts from this blog

Food Order System : Customer Service

2. Random Interview Question