Showing posts with label Microservices Interview. Show all posts
Showing posts with label Microservices Interview. Show all posts

Wednesday, 10 June 2020

Microservices Interview Questions Part-1

1. Advantages and disadvantages of micro-services. Why to go for micro services architecture over monolithic architecture.

The Advantages of Microservices
The advantages of microservices seem strong enough to have convinced some big enterprise players such as Amazon, Netflix, and eBay to adopt the methodology. Compared to more monolithic design structures, microservices:
       Improve fault isolation: Larger applications can remain mostly unaffected by the failure of a single module.
       Eliminate vendor or technology lock-in: Microservices provide the flexibility to try out a new technology stack on an individual service as needed. There won’t be as many dependency concerns and rolling back changes becomes much easier. With less code in play, there is more flexibility.
       Ease of Understanding: With added simplicity, developers can better understand the functionality of a service.

The Disadvantages of Microservices
Microservices may be a hot trend, but it does not come without its drawbacks.
Here’s a list of some potential pain areas associated with microservices designs:
       Developing distributed systems can be complex. Since everything is now an independent service, you have to carefully handle requests traveling between your modules. In one such scenario, developers may be forced to write extra code to avoid disruption. Over time, complications will arise when remote calls experience latency.
       Multiple databases and transaction management can be painful.
       Testing a microservices-based application can be cumbersome. In a monolithic approach, we would just need to launch our WAR on an application server and ensure its connectivity with the underlying database. With microservices, each dependent service needs to be confirmed before testing can occur.
       Deploying microservices can be complex. They may need coordination among multiple services, which may not be as straightforward as deploying a WAR in a container. Of course, with the right kind of automation and tools, all the above drawbacks can be addressed.

2. What are Discovery Register in Microservices Architecture?
In the microservices world, Service Registry and Discovery play an important role because we most likely run multiple instances of services and we need a mechanism to call other services without hardcoding their hostnames or port numbers. In addition to that, in Cloud environments service instances may come up and go down anytime. So we need some automatic service registration and discovery mechanism. Spring Cloud provides Service Registry and Discovery features, as usual, with multiple options. We can use Netflix Eureka or Consul for Service Registry and Discovery.

3. What are the Container in microservices?
Containers are packages of your software that includes everything that it needs to run, like code, dependencies, libraries, binaries, and more. Docker is one of the popular choices for building and running containers, but Kubernetes is quickly becoming the standard that is used to orchestrate multiple containers in enterprise environments. Compared to Virtual Machines, containers share the OS kernel instead of having a full copy of it – like making multiple VMs in a single host. Although it is possible to put your microservices in multiple VMs, containers are commonly used in this case since it takes up less space and is faster to boot up.

4. How Communication between Microservices happens.
 There are two ways that I know of through which you can communicate with other Microservices
       Rest Template
       Feign Client

5. Difference Between Rest Template and Feign Client.
RestTemplate is used for making the synchronous call. When using RestTemplate, the URL parameter is constructed programmatically, and data is sent across to the other service. In more complex scenarios, we will have to get to the details of the HTTP APIs provided by RestTemplate or even to APIs at a much lower level.
Feign is a Spring Cloud Netflix library for providing a higher level of abstraction over REST-based service calls. Spring Cloud Feign works on a declarative principle. When using Feign, we write declarative REST service interfaces at the client and use those interfaces to program the client. The developer need not worry about the implementation.

6. List the Microservices design patterns?
1.Aggregator Microservice
In its The simplest form, Aggregator would be a simple webpage that invokes multiple services to achieve the functionality required by the application.
2.Chained Microservice Design Pattern
Chained microservice design pattern produce a single consolidated response to the request. In this case the request from the client received by Service A, which then Communicating with service B, which in turn may be communicating with service C. All are likely using a synchronous HTTP request / response messaging.
3.Branch Microservice Design Pattern
Branch microservice design pattern extends Aggregator design pattern and allows simultaneous response processing from two likely mutually exclusive, chains of microservices. This Pattern can also be used to call different chains, or a single chain based on the business needs.
4.Shared Data Microservice Design Pattern
One of the design principles of microservice is autonomy. That means the service is full-stack and has control of all the components-UI, middleware, persistence, transaction. This allows the service to be polyglot and use the right tool for the right job. For example, if a No Sql data store can be used if that is more appropriate instead of jamming that data in Sql Database.
However, a typical problem, especially when refactoring from an existing monolithic application, is a database normalization such that each microservice has the right amount of data- nothing less and nothing more. Even if only a sql database is used in the monolithic application, deformalizing the database would lead to duplication of data and possibly inconsistency. In a transaction phase some applications may benefit from a shared data microservice design pattern.
In this design pattern, some microservices are likely in a chain, may share caching and database stores. This would only make sense if there is a strong coupling between two services. Some might consider this an anti-pattern but business needs might require in some cases to follow this. This would certainly be an anti-pattern for greenfield applications that are based upon microservices.
5.Asynchronous Messaging Microservice Design pattern
While Rest design pattern is quite prevalent, and well understood, but it has the limitation of being synchronous and thus blocking asynchrony can be achieved but that is done in application specific way. Some microservice architectures may elect to use message queues instead of rest request/response because of that.
6.Proxy Microservice Design Pattern
Proxy microservice design pattern is a variation of aggregator. In this case no aggregation needs to happen on the client but a different microservice may be invoked based on the business needs.
7.Event Sourcing Microservice Design Pattern
The event sourcing design pattern creates events regarding the changes in the application state. Also, these events are stored as a sequence of events to help the developers track which change was made when. So, with the help of this, you can always adjust the application state to cope up with the past changes. You can also query these events, for any data change and simultaneously publish these events from the event store. Once the events are published, you can see the changes of the application state on the presentation layer.
8.Circuit Breaker Pattern
As the name suggests, the Circuit Breaker design pattern is used to stop the process of request and response if a service is not working. So, for example, let’s say a client is sending a request to retrieve data from multiple services. But, due to some issues, one of the services is down. Now, there are mainly two problems you will face: first, since the client will not have any knowledge about a particular service being down, the request will be continuously sent to that service. The second problem is that the network resources will be exhausted with low performance and bad user experience.
9.Command Query Responsibility Segregator (CQRS) Design Pattern
Every microservices design has either the database per service model or the shared database per service. But, in the database per service model, we cannot implement a query as the data access is only limited to one single database. So, in such scenario you can use the CQRS pattern. According to this pattern, the application will be divided into two parts: Command and Query.
10.Decomposition Design Pattern
Microservices are developed with an idea on developers mind to create small services, with each having their own functionality. But, breaking an application into small autonomous units has to be done logically. So, to decompose a small or big application into small services, you can use the Decomposition patterns.

7. What is Containerization?
Containerization is a lightweight alternative to full machine virtualization that involves encapsulating an application in a container with its own operating environment. This provides many of the benefits of loading an application onto a virtual machine, as the application can be run on any suitable physical machine without any worries about dependencies.
Containerization has gained recent prominence with the open-source Docker. Docker containers are designed to run on everything from physical computers to virtual machines, bare-metal servers, OpenStack cloud clusters, public instances and more.

8. What is Docker?
 Docker is a tool designed to make it easier to create, deploy, and run applications by using containers. Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies, and ship it all out as one package. By doing so, thanks to the container, the developer can rest assured that the application will run on any other Linux machine regardless of any customized settings that machine might have that could differ from the machine used for writing and testing the code.
 In a way, Docker is a bit like a virtual machine. But unlike a virtual machine, rather than creating a whole virtual operating system, Docker allows applications to use the same Linux kernel as the system that they're running on and only requires applications be shipped with things not already running on the host computer. This gives a significant performance boost and reduces the size of the application.

9. what is container orchestration?
Container orchestration is all about managing the lifecycles of containers, especially in large, dynamic environments. Software teams use container orchestration to control and automate many tasks:
        Provisioning and deployment of containers
       Redundancy and availability of containers
       Scaling up or removing containers to spread application load evenly across host infrastructure
       Movement of containers from one host to another if there is a shortage of resources in a host, or if a host dies
       Allocation of resources between containers
       External exposure of services running in a container with the outside world
       Load balancing of service discovery between containers
       Health monitoring of containers and hosts
       Configuration of an application in relation to the containers running it
 
10.Explain the Netflix Components.
Service Discovery Server: Netflix Eureka
Edge Server: Netflix Zuul.
Central configuration server: Spring cloud config server.
Dynamic routing and load balancer: Netflix ribbon.
Oauth 2.0 protected Apis: Spring cloud + spring security OAuth 2

Monitoring Netflix Hystrix dashboard and turbine.


Friday, 22 May 2020

Typical MicroServices Interview

1. Explain briefly about your project experience ​ .

2. Explain about oops concept and how you implemented in your project.  

3. I have a class A having main method, also I have another class B extends A when compiling B will it be executed or not?.

Yes, It will get executed. 
public class Test2 {         

public static void main(String[] args) {  
System.out.println("Called Test 2");         }   } 

public class Test4 extends Test2  {  } 

output: Called Test 2 

4. What will happen when a method is called inside the same method. Who Checks and stop the program termination. 

eg:  public class Test2  { 

public void greet(){ 
greet(); 
}         
public static void main(String[] args) {
  Test2 test2 = new Test2();
  test2.greet();  
       } 
  } 

The above Code throws Exception in thread "main" java.lang.StackOverflowError. Which means The StackOverflowError extends the VirtualMachineError class, which indicates that the JVM is broken, or it has run out of resources and cannot operate. Furthermore, the the VirtualMachineError extends the Error class, which is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur. 

When a function call is invoked by a Java application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no 
space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM). 

The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion is considered as a powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError to be avoided. 

5. If I have a static method in both parent class and extended class and while creating the object reference for the child method which method will be invoked.? 

private, final and static methods and variables use static binding and bonded by the compiler while overridden methods are bonded during runtime based upon the type of runtime object 

Hence the method in the parent class is called also the compiler throws the warnings."The static method greet() from the type Test2 should be accessed in a static way" 

6. How many objects are created when (Parent)Test2 test2 = new (child)Test4(); 

In inheritance, subclass acquires super class properties. An important point to note is, when subclass object is created, a separate object of super class object will not be created. Only a subclass object object is created that has super class variables. 

7. Explain static binding? 

Static Binding: The binding which can be resolved at compile time by compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time . 

Why binding of static, final and private methods is always a static binding?  Static binding is better performance wise (no extra overhead is required). Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static. 

8. I have two class and methods with different argument how do you call this during the runtime. 

public class ReflectionDemo1 {


    public static void main(String[] args) {

        System.out.println(greet("Syed Ghouse Habib", 1));
    }
    public static String greet(String string, long log) {
        return string + log;
    }
}

public class ReflectionDemo2 {
    public static void main(String[] args) {

        System.out.println(greet("Syed Ghouse Habib"));
    }
    public static String greet(String string) {
        return string;
    }
}

It can be called using the reflection.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class InvokeMain {
    public static void main(String...args) {
        try {
            for (String arg: args) {
                Class << ? > c = Class.forName(arg);
                Class[] argTypes = new Class[1];
                argTypes[0] = String[].class;
                Method main = c.getDeclaredMethod("main", argTypes);
                String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
                System.out.format("invoking %s.main()%n", c.getName());
                main.invoke(null, (Object) mainArgs);
            }

            // production code should handle these exceptions more gracefully } catch (ClassNotFoundException x) {     x.printStackTrace(); } catch (NoSuchMethodException x) {     x.printStackTrace(); } catch (IllegalAccessException x) {     x.printStackTrace(); 
        } catch (InvocationTargetException x) {
            x.printStackTrace();
        }
    }
}

9. What will happen when the Employee object with the same value is added to the set

Having only the equals method. It will have two objects created. When we have only the hashcode method. It will have two objects created. It will have only one entry when both the methods are available. 

10. Write a program to sum the value from the given alphanumeric string. 

sampleString = "pq12s56"

import java.util.stream.Collectors;

public class StringSummer {

    public static void main(String args[]) {
        String sampleString = "pq12s56";
        int sum8 = 0; //using java8 
        sum8 = sampleString.chars().filter(val - > Character.isDigit((char) val)).mapToObj(num - > Character.getNumericValue(num)).collect(Collectors.summingInt(Integer::intValue));
        System.out.println(sum8);

        int sum = 0; //using java 7
        char[] charVal = sampleString.toCharArray();
        for (char c: charVal) {
            if (Character.isDigit(c)) {
                sum = sum + Character.getNumericValue(c);
            }

        }
        System.out.println(sum);
    }
}

11. Explain memory management in java?.

Runtime data area in JVM can be divided as below, 

Method Area: Storage area for compiled class files. (One per JVM instance) 

Heap: Storage area for Objects. (One per JVM instance) 

Java stack: Storage area for local variables, results of intermediate operations. (One per thread) 

PC Register: Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined. (One per thread) 

Native method stacks : Helps in executing native methods (methods written in languages other than Java). (One per thread) 

Following are points you need to consider about memory allocation in java. 

Note: Object and Object references are different things. 

1)There is new keyword in java used very often to create a new objects. But what new does is allocate memory for the object of class you are making and returns a reference. 

That means whenever you create an object as static or local, it gets stored in HEAP. 

2) All the class variable primitive or object references (which is just a pointer to location where object is stored i.e. heap) are also stored in heap. 

3) Classes loaded by classloader and static variables and static object references are stored in a special location in heap which permanent generation. 

4) Local primitive variables, local object references and method parameters are stored in Stack. 

5) Local Functions (methods) are stored in stack but Static functions(methods) goes in permanent storage. 

6) All the information related to a class like the name of the class, Object arrays associated with the class, internal objects used by JVM (like java/lang/Object), and optimization information goes into the Permanent Generation area. 

7) To understand stack, heap, data you should read about Processes and Process Control Block in Operating Systems. 


12. Explain the initial capacity of ArrayList?. How would you force to create an array of capacity 8? 

In java 8 default capacity of ArrayList is 0 until we add at least one object into the ArrayList object (You can call it lazy initialization). 

Now question is why this change has been done in JAVA 8? 

The answer is to save memory consumption. Millions of array list objects are created in real-time java applications. Default size of 10 objects means that we allocate 10 pointers (40 or 80 bytes) for the underlying array at creation and fill them in with nulls. An empty array (filled with nulls) occupy lot of memory . 

Lazy initialization postpones this memory consumption till moment you will actually use the array list. 

List<String> s = new ArrayList<>(8); 

This statement will create the array of inital capacity 8. 

13. What is the algorithm used in Java GC. 

Mark & sweep algoritm. 

14.what are the different types of method avaliable in  

1. GET Method HTTP GET method used to retrieve information from the REST API.We should not use this method to change any information or the resource.GET should be idempotent, meaning regardless of how many times it repeats with the same parameters, the results are the same. 

2. POST Method This method in the REST API should only be used to create a new resource.In some cases, POST method is used to update entity but this operation is not very frequent.POST API call is not idempotent nor safe and should be used with care. 

3. PUT Method If we want to update an existing resource, PUT method should be used for this operation.PUT method has some features as compare to the POST method and we should keep those in mind · PUT method is idempotent.This means the client can send the same request multiple time and as per HTTP spec, this has exactly the same effect as sending once. (This is for us to make sure PUT behaves correctly every time) 

4. DELETE Method DELETE method should be used to remove a given resource.Similiar to PUT method, DELETE operation is idempotent.If a resource is deleted any later request will change anything in the 
system and it should return 404 response.DELETE can be a long-running or asynchronous request.

 5. PATCH Method Partial update to a resource should happen through PATCH method.To differentiate between PATCH and PUT method, PATCH request used to partially change a given resource while PUT used to replace existing resource.There are few things to keep in mind while using PATCH method. · Support for PATCH in browsers, servers and web applications are not universal, this can post some challenges. · Request payload for Patch is not simple and a client is required to send information to differentiate between the new and original documents. 

15. Difference between put and post method. 

PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)! POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent. 

16. How does the springboot works. 

From the run method, the main application context is kicked off which in turn searches for the classes annotated with @Configuration, initializes all the declared beans in those configuration classes, and based upon the scope of those beans, stores those beans in JVM, specifically in a space inside JVM which is known as IOC container. After the creation of all the beans, automatically configures the dispatcher servlet and registers the default handler mappings, messageConverts, and all other basic things. 

Basically, spring boot supports three embedded servers:- Tomcat (default), Jetty and Undertow. 

You can add cross filters in spring boot in one of the configuration files as 

@Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { 

    @Override     public void addCorsMappings(CorsRegistry registry) {         registry.addMapping("/api/**");     } } 

17.What are the Embeded servers in spring boot and which one is default. 

Tomcat (default), Jetty and Undertow. 

18. Difference between spring mvc and spring boot, is dispatcher servlet not used in the springboot? 

Spring MVC is a complete HTTP oriented MVC framework managed by the Spring Framework and based in Servlets. It would be equivalent to JSF in the JavaEE stack. The most popular elements in it are classes annotated with @Controller, where you implement methods you can access using different HTTP requests. It has an equivalent @RestController to implement REST-based APIs. 

Spring boot is a utility for setting up applications quickly, offering an out of the box configuration in order to build Spring-powered applications. As you may know, Spring integrates a wide range of different modules under its umbrella, as spring-core, spring-data, spring-web (which includes Spring MVC, by the way) and so on. With this tool you can tell Spring how many of them to use and you'll get a fast setup for them (you are allowed to change it by yourself later on). So, Spring MVC is a framework to be used in web applications and Spring Boot is a Spring based production-ready project initializer. 


You understood it right. 

@Configuration @Configuration is an analog for xml file. Such classes are sources of bean definitions by defining methods with the @Bean annotation. 

@Configuration is: 

not required, if you already pass the annotated class in the sources parameter when calling the SpringApplication.run() method; required, when you don't pass the annotated class explicitly, but it's in the package that's specified in the @ComponentScan annotation of your main configuration class. For readability, classes that are even explicitly passed as sources may anyway be annotated with @Configuration - just to show the intentions more clearly. 

Your current class is not really source of bean definitions, because it doesn't have any, but if you had @Bean annotated methods, Spring would see them. 

@EnableAutoConfiguration Can be used with or without @Configuration. It tells Spring to setup some basic infrastructure judging by what you have in the classpath. It's done by invoking a so called import class that's 
derived from the value of the @Import annotation that @EnableAutoConfiguration includes. Only one class should be annotated with @EnableAutoConfiguration, duplicating it doesn't do anything. 

19.what is a stream in java 8 and what are its features?. 

Java provides a new additional package in Java 8 called java.util.stream. This package consists of classes, interfaces and enum to allows functional-style operations on the elements. You can use stream by importing java.util.stream package. 

Stream provides following features: 

Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations. Stream is functional in nature. Operations performed on a stream does not modify it's source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection. Stream is lazy and evaluates code only when required. The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source. You can use stream to filter, collect, print, and convert from one data structure to other etc. In the following examples, we have apply various operations with the help of stream. 

20. Draw microservices componets. 


21. How to implement the retry mechanism for the microservices. 

@SpringBootApplication
@EnableRetry
public class So52193237Application {

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

    @Bean
    public ApplicationRunner runner(Foo foo) {
        return args - > {
            try {
                foo.exec();
            } catch (Exception e) {
                try {
                    foo.exec();
                } catch (Exception ee) {
                    Thread.sleep(11000);
                    try {
                        foo.exec();
                    } catch (Exception eee) {

                    }
                }
            }
        };
    }

    @Component
    public static class Foo {

        private static final Logger LOGGER = LoggerFactory.getLogger(Foo.class);

        private final Bar bar;

        public Foo(Bar bar) {
            this.bar = bar;
        }

        @CircuitBreaker(maxAttempts = 1, openTimeout = 10000, resetTimeout = 10000)
        public void exec() throws TypeOneException {
            LOGGER.info("Foo.circuit");
            this.bar.retryWhenException();
        }

        @Recover
        public void recover(Throwable t) throws Throwable {
            LOGGER.info("Foo.recover");
            throw t;
        }

    }

    @Component
    public static class Bar {

        private static final Logger LOGGER = LoggerFactory.getLogger(Bar.class);

        @Retryable(value = {
            TypeOneException.class
        }, maxAttempts = 3, backoff = @Backoff(2000)) public void retryWhenException() throws TypeOneException {
            LOGGER.info("Retrying");
            throw new TypeOneException();
        }

        @Recover
        public void recover(Throwable t) throws Throwable {
            LOGGER.info("Bar.recover");
            throw t;
        }

    }

}

22. What are the types of exceptions you have handled in your application? 

23. Do you like to work in a team or an individual contributor? 

24. Do you like to learn about new technologies?. 

25. Have you heard of cucumber?. 

26. What you will do in your free time?. 

27. If you have a conflict with one of your college how you will resolve it?. 

28. If the requirements are not clear what you will do first?. 

29. Any Questions for me? 

x