Microservice Interview Question

In this post, we will share the Microservice Interview Questions. Our content is well researched and collected from the employee who have cleared the Java interview.

1. What are microservices?

Micro services architecture is an approach in which major features and functions of the applications are breaking down into smaller specialised services. As we have seen,  we code all features of the applications into a single executable applications in monolithic architecture which gets difficult to manage at certain point in time when applications becomes complex.

In Microservices, each service typically focuses on a single task, such as user authentication, order processing, or database management. They communicate with each other through well-defined APIs often using lightweight protocols such as HTTP or messaging queues.

Lets understand this with a simple example:

We have to make our Amazon Website into micro services then I would create Services like:

  • User Service: Manages user accounts, authentication, and their order history.
  • Product Catalog Service: handles product information, search, and recommendations.
  • Cart Service: Manages shopping carts and interactions with products.
  • Payment Service: Processes payments and handles transactions.
  • Review Service: Manages product reviews and ratings.
  • Shipping Service: Manages order fulfillment and shipping information.

2. What are the benefits of using microservices?

Microservices provides flexibility and agility through modular architecture, fostering faster development cycles and easier maintenance.

Microservices architecture provides following benefits:

  • Scalability: If one service is experiencing high demand then it can be scaled up without affecting other services, leading to better resource utilization and cost efficiency.
  • Flexibility: Each microservice can be developed, deployed, and updated independently. This enables teams to use different programming languages, frameworks, and tools best suited for each service’s requirements. It also facilitates faster development cycles and easier experimentation with new technologies.
  • Resilience: Microservices provides fault tolerant. Our application will keep running even if one service fails as all services are deployed independently, reducing the impact of failures and improving overall system resilience.. In an Amazon, if AmaonPay service fails still you can browse and place order. Although, you can’t utilise AmaonPay benefits.
  • Improved Developer Productivity: Microservices enable smaller, focused teams to work on specific services independently. This autonomy fosters faster development cycles, quicker time-to-market, and easier maintenance. Developers can also use modern development practices like continuous integration and continuous delivery (CI/CD) more effectively.

3. What are the differences between microservices and monolithic architecture?

Microservices and Monolithic architecture are two contrasting approaches to build software applications. Here are the key differences between them:

  • Architecture Style:
    • Microservices: In Microservices architecture, break the application into smaller, independent services, each representing a specific business function. These services communicate with each other through APIs and can be developed, deployed, and scaled independently.
    • Monolithic: In a monolithic architecture, the entire application is developed as a single unit. All components, including user interface, business logic, and data access layers, are tightly integrated into a single codebase and deployed together.
  • Scalability:
    • Monolithic: Scaling a monolithic application often involves replicating the entire application stack, including components that may not require additional resources. This can lead to inefficiencies and increased costs.
    • Microservices: In Microservices Architecture, we can scale up or scale down individual services which experiencing high traffic. This approach provides better resource utilisation and cost efficiency.
  • Technology Stack:
    • Monolithic: Monolithic applications typically use a single technology stack for the entire application.
    • Microservices: Microservices architecture allows for technology diversity. Different services can be developed using different programming languages, frameworks, and databases based on their specific requirements.
  • Deployment:
    • Monolithic: Deploying changes to a monolithic application often involves deploying the entire application at once. This can increase the risk of downtime.
    • Microservices: Microservices enable independent deployment of individual services. Changes to one service can be deployed without affecting others, reducing the risk and impact of deployments.

4. What are the differences between synchronous and asynchronous communication in microservices?

In a microservices architecture, communication between services can either be Synchronous or Asynchronous. Both have their advantages and disadvantages, and the choice of which to use depends on the specific scenario.

  • Synchronous Communication:
    • In Synchronous communication, the sender of a request waits for a response from the receiver before proceeding further.
    • Common synchronous communication mechanisms include HTTP request/response, RPC (Remote Procedure Call), and synchronous messaging protocols like SOAP (Simple Object Access Protocol).
  • Asynchronous Communication:
    • In Asynchronous communication, the sender of a message doesn’t wait for an immediate response from the receiver. Here, the sender sends a message and continues with its own processing without waiting for a response.
    • This is similar to sending an email, we send it and continue with our work without waiting for an instant reply.
    • Common asynchronous communication mechanisms include message queues like MQ, publish-subscribe systems like Kafka.

5. How do you handle versioning of APIs in a microservices environment?

In Spring Boot, you can handle API versioning using various approaches. Here’s how you can implement API versioning:

  • URL Versioning:
    • Define different endpoints for each version of the API. For example:
  • Parameter Versioning:
    • You can include the version number as a request parameter and handle it accordingly in your controller.
  • Header Versioning:
    • Clients can specify the desired API version in a custom header and you can read this header in your controller.

6. Explain the concept of idempotence in microservices?

An operation is considered idempotent if performing it multiple times produces the same result as performing it once. This doesn’t necessarily mean that nothing happens after the first operation, but rather that subsequent operations don’t produce any new side effects.

Let’s consider the example of an HTTP DELETE request in the context of a MicroServices. If a client issues a DELETE request to remove a specific resource, the first request might delete the resource, while subsequent identical requests will have no further effect since the resource is already deleted. Regardless of how many times the client sends the DELETE request, the end state remains the same: the resource is deleted.

7. What are the drawbacks of microservices architecture?

As we have seen, microservices architecture offers numerous benefits such as scalability, agility, and resilience but it also comes with its own set of challenges and drawbacks:

  • Increased Complexity: Managing a large number of microservices, each with its own codebase, deployment pipeline, and dependencies can become challenging.
  • Distributed Systems Complexity: Microservices rely on network communication, which introduces issues such as latency, network failures, and security concerns.
  • Operational Overhead: Operating and managing multiple microservices involves overhead in terms of monitoring, logging, deployment automation, and infrastructure management. DevOps teams need to put lot of effort to manage them effectively.
  • Data Management Challenges: Microservices often have their own databases, leading to data management challenges such as maintaining data consistency across services.

8. Can you describe a scenario where you would choose a monolithic architecture over microservices?

Here are some situations in which we may choose monolithic architecture:

Scenario 1 – If you have few resources, a monolithic architecture might be an appropriate option since it is easy to create and manage.

Scenario 2 – If your system is relatively simple and does not have many components, a monolithic architecture might work well.

9. Can you explain the difference between stateless and stateful microservices?

Stateless microservices do not maintain any state across calls. They process requests without retaining any state information. This means stateless microservices are “forgetful.” Stateless microservices are typically easier to deploy, manage, and scale since they don’t require shared state management or synchronization mechanisms. Examples of stateless microservices include APIs for user authentication, static content delivery, or lightweight processing tasks.

In contrast to stateless microservices, Stateful microservices maintain some form of state between requests. This state could be stored in a database, cache, or in-memory data store. Examples of stateful microservices include shopping carts, user sessions, or real-time collaboration features.

10. What is circuit breaker pattern?

Circuit Breaker is one of the Microservice Design Patterns for designing highly resilient and fault tolerant distributed system by using a library called resilience4j.

Circuit Breaker pattern is used to prevent calling a microservice in case of abnormal behaviour in that service (service down/unavailable or timeout etc). This pattern can help the client’s side ignore handling failed requests and give the service, some time to recover.

Let’s consider one example in which Service B depends on Service C which has an issue. With this Retry Pattern, Service B will be sending multiple requests again and again to Service C assuming it will work. When there are hundreds of concurrent requests are sent to Service B which in turn would be bombarding Service C with Retry requests.

This is where Circuit Breaker Pattern helps us. When the requests to Service C are continuously failing, what is the point of sending the requests to Service C? Circuit Breaker simply skips the calls to Service C and goes with the fall back method / default values instead for certain duration which is configurable. In this case, it does not bombard Service C continuously. It gives Service C sometime to recover from failure. Circuit Breaker Pattern retries after some time and so on.

11. What is the purpose of an API gateway in microservices?

An API gateway serves as a central entry point for clients (such as web browsers, mobile devices, etc.) to access various microservices within a system. It provides several benefits such as:

  1. Unified Entry Point: By providing a single entry point for clients, an API gateway simplifies the client-side experience. Clients don’t need to know the specific endpoints or protocols of individual microservices, reducing complexity and making it easier to consume services.
  2. Service Aggregation: The API gateway can aggregate multiple microservices into a single API, allowing clients to access different functionalities through a unified interface. This simplifies client-server communication and reduces the number of network round trips required for a single operation.
  3. Protocol Translation: It can translate between different communication protocols, allowing clients to communicate using their preferred protocol while enabling microservices to use different ones internally. This flexibility promotes interoperability and allows for the gradual adoption of new technologies without disrupting existing systems.
  4. Load Balancing: An API gateway can distribute incoming requests across multiple instances of a microservice to ensure optimal performance and scalability. By evenly distributing the workload, it helps prevent individual services from becoming overloaded and improves overall system reliability.
  5. Security: The API gateway serves as a centralized point for enforcing security policies such as authentication, authorization, and encryption. It can handle tasks like API key validation, access control, and token-based authentication, reducing the burden on individual microservices and promoting consistent security practices across the system.
  6. Monitoring and Analytics: It provides logging, monitoring, and analytics capabilities to track request patterns, performance metrics, and errors across the system. This visibility enables administrators to identify and troubleshoot issues more effectively, leading to improved reliability and performance.
  7. Caching: The API gateway can cache responses from microservices to reduce latency and improve scalability. By caching frequently accessed data, it reduces the load on backend services and improves overall system performance, especially during periods of high traffic.
  8. Rate Limiting and Throttling: It can enforce rate limits and implement throttling to prevent abuse or excessive usage of resources. By controlling the rate of incoming requests, it helps maintain system stability, protects against denial-of-service attacks, and ensures fair access to services for all clients.

12. What is service discovery and how we can implement in microservices?

Service discovery in microservices is like a map that helps services find each other in a big system. It’s important because in microservices, services can move around or change a lot. With service discovery, each service tells a central place where it is and where other services are. This makes it easier for services to talk to each other without needing to know all the details. Tools like Netflix Eureka or Consul help with this. They work like a big address book where services write down where they are, and other services can look up their address when they need to talk to them. This helps make the system flexible and able to change without breaking.

13. How do microservices handle security and authentication?

Microservices keep information safe and only let authorized people see it by using different security methods.

API gateway: Microservices often use an API gateway as the main way to get into the system. This gateway checks who’s trying to come in and makes sure they’re allowed in by following security rules.

OAuth and JWT: These are common ways to check if someone is who they say they are before letting them into the system. They also give out special codes called access tokens to make sure that communication between services stays safe.

Role-based access control (RBAC): RBAC decides who gets to see what based on their job or role. It’s like a rulebook that says who can go where in the system.

14. What is Oauth ?

OAuth is a type of security system that lets different services share information without sharing passwords. It uses special codes called tokens to do this securely. With OAuth, users can let one app do things in another app without giving away their password. They can also decide exactly what the app is allowed to do, which makes things clearer and safer.

OAuth helps apps work together even if they’re not directly connected. It keeps track of who’s allowed to do what, which makes it easier for apps to talk to each other. It can handle lots of different situations, like when a server needs to talk to another server, or when an app needs to talk to a server. And it can be combined with other systems to handle even more complex tasks.

15. What is the difference between OAuth and OAuth2 ?

OAuth and OAuth2 are protocols used to securely allow one application or service to access another application or service. OAuth is the original version of this protocol, while OAuth2 is an updated version. OAuth2 is considered more secure than OAuth because it uses stronger encryption methods. OAuth2 is also more flexible because it offers a wider range of authorization grants, which are different ways for an application to obtain an access token.

Another difference is that OAuth2 allows for “implicit” flow over plain HTTP, meaning it can work without a secure connection (HTTPS). However, this is not recommended due to security risks.

In summary, OAuth2 is an improved version of OAuth that addresses some of the security and flexibility issues present in the original protocol.

16. What is the need of externalize the application configuration?

When a service talks to other services or databases, it needs to know where to find them. But in different environments like development or production, these locations can change. If we have to change these locations in the code every time, it’s a hassle. So, how do we make sure our code doesn’t need changing every time the location changes?

A solution is to externalise all the configuration.

  1. Externalizing Configuration: Move all configuration settings, including endpoint URLs and credentials, out of the application code and into external configuration files.
  2. Dynamic Configuration Loading: Configure the application to load these externalized configuration settings either during startup or dynamically while the application is running.
  3. Spring Cloud Config Server: Utilize Spring Cloud Config Server, a centralized configuration server, to externalize configuration properties to a source control repository like GitHub. This allows applications to retrieve configuration properties as environment variables during startup or dynamically refresh them without requiring a server restart.

By externalizing configuration and leveraging tools like Spring Cloud Config Server, applications can achieve greater flexibility and maintainability, as configuration changes can be made without needing to modify and redeploy the application code.

17. What is Single Responsibility Principle in Micro-Service ?

The Single Responsibility Principle (SRP) dictates that a class should have only one reason to change at any given time. Adhering to this principle yields numerous benefits, including reduced complexity, enhanced flexibility, extensibility, and ease of maintenance. It also facilitates smoother modifications to classes without introducing errors.

In the context of micro-services architecture, a micro-service following SRP is simpler to maintain and update compared to one with multiple responsibilities. Such a micro-service is less likely to create conflicts with other micro-services.

Programmers must prfioritize SRP when designing micro-services based applications, ensuring that each micro-service has a single responsibility and avoiding the inclusion of multiple responsibilities within a single micro-service.

Leave a comment