Microservices Interview Questions Answers 3+
Microservices Interview Questions Answers 3+
If you have a business focus and you want to solve a use case or a problem efficiently without the
boundaries of technology, want to scale an independent service infinitely, highly available stateless
services which are easy to maintainable and managed as well as independently testable then we
would go ahead and implement Microservices architecture.
If you already have a monolith application and it grows to an extent where there are problems in
scaling or we are not able to reutilize the components/modules/services across different
projects/platforms and there is a need to do so. As well as at the same time implementing new
features is painful and more error-prone and it is difficult to scale further.
For new applications where implementation has not started yet started, we can think of a business
case to be efficiently implemented, which can be easily maintainable, testable and scalable in the
future and might be used across other projects/products/platforms at the same time.
One should have unit and integration tests where all the functionality of a microservice can be
tested. One should also have component based testing.
One should have contract tests to assert that the expectations by the client is not breaking. End-to-
end test for the microservices, however, should only test the critical flows as these can be time-
consuming. The tests can be from two sides, consumer-driven contract test and consumer-side
contract test.
You can also leverage Command Query Responsibility Segregation to query multiple databases and
get a combined view of persisted data.
4.What is service discovery? And how is it helpful?
In a cloud environment where docker images are dynamically deployed on any machine or IP + Port
combination, it becomes difficult for dependent services to update at runtime. Service discovery is
created due to that purpose only.
Service discovery is one of the services running under microservices architecture, which registers
entries of all of the services running under the service mesh. All of the actions are available through
the REST API. So whenever the services are up and running, the individual services registers
themselves to service discovery service and service discovery services maintains heartbeat to make
sure that those services are alive. That also serves the purpose of monitoring services as well.
Service discovery also helps in distributing requests across services deployed in a fair manner.
Instead of clients directly connecting to load balancer, in this architectural pattern the client
connects to the service registry and tries to fetch data or services from it.
Once it gets all data, it does load balancing on its own and directly reaches out to the services it
needs to talk to.
This can have a benefit where there are multiple proxy layers and delays are happening due to the
multilayer communication.
In server-side discovery, the proxy layer or API Gateway later tries to connect to the service registry
and makes a call to appropriate service afterward. Over here client connects to that proxy layer or
API Gateway layer.
One can scale the system by increasing the number of instances of service by bringing up more
containers.
One can also apply to cache at microservice layer which can be easy to manage as an invalidation of
the cache can be done very easily as the microservice will be the single source of truth.
Caching can also be introduced at the API Gateway layer where one can define caching rules like
when to invalidate the cache.
One can also shut down some containers when the requirement is less. That is, scale down
There is no single definition that fully describes the term "microservices". Some of
8.
Difference between Microservices and SOA
SOA started gaining ground due to its distributed architecture approach and it
Both (SOA and Microservices) of these architectures share one common thing that
they both are distributed architecture and both allow high scalability. In both, service
components are accessed remotely through remote access protocol (RMI, REST,
SOAP, AMQP, JMS, etc.). both are modular and loosely coupled by design and offer
high scalability. Microservices started gaining buzz in late 2000 after the emergence
1. SOA uses Enterprise Service Bus for communication, while microservices uses
REST or some other less elaborate messaging system (AMQP, etc). Also,
microservice follow "Smart endpoints and dumb points", which means that
monoliths.
3. Generally, microservices are significantly smaller than what SOA tends to be. Here we
are not talking about the codebase here because few languages are more verbose than
the other ones. We are talking about the scope (problem domain) of the service itself.
4. Microservices should own their own data while SOA may share a common database. So
one Microservices should not allow another Microservices to change/read its data
directly.
case of microservices. Each microservice can have its own technology stack based on its
Microservice should manage its own functional domain and data model.
everything related to the domain is visible within context internally but opaque to
other bounded contexts. DDD deals with large models by dividing them into different
A single conceptual model for the entire organization is very tricky to deal with. The
only benefit of such a unified model is that integration is easy across the whole
1. At first, it's very hard to build a single model that works for the entire
organization.
4. Any large enterprise needs a model that is either very large or abstract.
model. Such a model, even if created, will lead to a lot of confusion across the
teams.
1. High Cohesion - Small and focussed on doing one thing well. Small does not
mean less number of lines of code because few programming languages are
more verbose than others, but it means the smallest functional area that a
independently, and reliability, due to the ability for a service to run even if
communicates with the rest of the domain by using an interface for that Bounded context.
6. Versioning for backward compatibility. Even multiple versions of same microservices can
example, if a microservices serving the comments and reviews for e-commerce fails, the
8. Decentralized data management with each service owning its database rather than a
single shared database. Every microservice has the freedom to choose the right type of
database appropriate for its business use-case (for example, RDBMS for Order
from unauthorized access. This is achieved using stateless security mechanisms like
Autonomous Deployments
of each other, so changing a service does not require coordination with other teams.
This can lead to significantly faster release cycles. It is very hard to achieve the
same thing in a realistic monolithic application where a small change may require
Culture Shift
Technology Diversification
Unlike in monolithic applications, microservices are not bound to one technology stack (Java,
.Net, Go, Erlang, Python, etc). Each team is free to choose a technology stack that is best suited
for its requirements. For example, we are free to choose Java for a microservice, c++ for others
DevOps Culture
correctly can lead to shorter development cycles and thus faster time to market.
12.
What is polyglot persistence? Can this idea be used in monolithic
applications as well?
Polyglot persistence is all about using different databases for different business
products in the market each for a specific business need, for example:
RDBMS
Relational databases are used for transactional needs (storing financial data,
MongoDB
Documented oriented databases are used for documents oriented needs (for e.g.
Cassandra/Amazon DynamoDB
Key-value pair based database (User activity tracking, Analytics, etc.). DynamoDB can store
Redis
In memory distributed database (user session tracking), its mostly used as a distributed cache
Neo4j
microservices architecture. Any decent-sized product will have a variety of needs which may not
be fulfilled by a single kind of database alone. For example, if there are no transactional needs
for a particular microservice, then it's way better to use a key-value pair or document-oriented
o/p, varying loads within our application tiers, distributed transactions, etc.”
3. How to make configuration changes across the large fleet of services with
minimal effort?
appropriately?
unexpectedly?
6. How to isolate a failed microservice and avoid cascading failures in the entire
ecosystem?
scale with safely. There are many benefits of microservices architecture over
file deployed in tomcat, websphere etc) and a client interface (JSP, etc.)
least one of these three components and deploy the new version to
monolith on multiple machines, by copying the big war/ear file again and
5.
6. As illustrated in the above example, a typical monolith eShop application is usually a big
like direct method invocation. One or more databases are shared among different
16.
How to convert the large application into microservices architecture?
Each software component should have single well-defined responsibility (a.k.a Single
Responsibility Principle) and the principle of Bounded Context (as defined by Domain
Product catalogue
products facets.
Inventory
Orders
Payments
Shipments
Demand generation
User Accounts
Recommendations
The client application (browser, mobile app) will interact with these services via API gateway and
17.
How to stop a Spring Boot based microservices at startup if it can not
connect to the Config server during bootstrap?
If you want to halt the service when it is not able to locate the config-server during
bootstrap.yml:
spring:
cloud:
config:
fail-fast: true
Using this configuration will make microservice startup fail with an exception when
We can enable a retry mechanism where microservice will retry 6 times before
build.gradle:-
...
dependencies {
compile('org.springframework.boot:spring-boot-starter-aop')
compile('org.springframework.retry:spring-retry')
...
}
18.
How to partition a large application into microservices architecture?
Each software component should have single well-defined responsibility (a.k.a Single
Responsibility Principle) and the principle of Bounded Context (as defined by Domain
For example, an e-shop can be partitioned into following microservices based on its
business capabilities:
Product catalogue
products facets.
Inventory
Orders
Payments
Shipments
Demand generation
Market products to relevant users.
User Accounts
Recommendations
Notifications
The client application (browser, mobile app) will interact with these services via the API gateway
necessary to represent the domain concept they own said by Martin Fowler
Microservices are usually small but not all small services are microservices. If any
service is not following the Bounded Context Principle, Single Responsibility Principle,
etc. then it is not a microservice irrespective of its size. So the size is not the only
In fact, size of a microservice is largely dependent on the language (Java, Scala, PHP)
Other communication protocols can also be used for integration like AMQP, JMS,
Kafka, etc.
Synchronous Communication
calls between microservices because networks are brittle and they introduce latency.
Ribbon - a client-side load balancer can be used for better utilization of resource on
the top of RestTemplate. Hystrix circuit breaker can be used to handle partial failures
should be avoided at any cost, instead, we shall opt for eventual consistency using
asynchronous communication.
Asynchronous Communication
In this type of communication, the client does not wait for a response, instead, it just
sends the message to the message broker. AMQP (like RabbitMQ) or Kafka can be
consistency
21.
What should be preferred communication style in microservices:
synchronous or asynchronous?
(anything that modifies the data) requests, using some reliable queue
Gateway Level. But this aggregation should not include any business logic
about the domain, it should not tell what to do (action) on this data.
backlog/technical debt.
in a certain fashion to complete a given task. The central system maintains the state
Microservice works like a State Machine and reacts based on the input from other
parts. Each service knows how to react to different events from other systems. There
where-ever possible.
Example
Let’s say we want to develop a microservice that will send product recommendation email in a
fictitious e-shop. In order to send Recommendations, we need to have access to user’s order
In Orchestration approach, this new microservice for recommendations will make synchronous
calls to order service and fetch the relevant data, then based on his past purchases we will
calculate the recommendations. Doing this for a million users will become cumbersome and will
Recommendation service will listen to this event and start building user recommendation. This is
a loosely coupled approach and highly scalable. The event, in this case, does not tell about the
There is no right answer to this question, there could be a release every ten minutes,
every hour or once a week. It all depends on the extent of automation you have at a
requirements - how small low-risk changes you care making in a single release.
(bounded context), and a given service is not affecting other microservices, you can
2. Github is well known for its aggressive engineering practices, deploying code
4. Many Google services see releases multiple times a week, and almost
24.
What are Cloud-Native applications?
encourages easy adoption of best practices in the area of continuous delivery and
DevOps, continuous delivery, microservices, and containers are the key concepts in
Microservices
small services. Each service is responsible for a specific business capability, runs in
its own process and communicates via HTTP REST API or messaging (AMQP).
DevOps
Continuous Delivery
Its all about automated delivery of low-risk small changes to production, constantly. This makes it
Containers
Containers (e.g. Docker) offer logical isolation to each microservices thereby eliminating the
problem of "run on my machine" forever. It’s much faster and efficient compared to Virtual
Machines.
25.
How will you develop microservices using Java?
Spring Boot along with Spring Cloud is a very good option to start building
microservices using Java language. There are a lot of modules available in Spring
Cloud that can provide boiler plate code for different design patterns of
microservices, so Spring Cloud can really speed up the development process. Also,
Spring boot provides out of the box support to embed a servlet container
(tomcat/jetty/undertow) inside an executable jar (uber jar), so that these jars can be
run directly from the command line, eliminating the need of deploying war files into
a servlet container.
You can also use Docker container to ship and deploy the entire executable package
onto a cloud environment. Docker can also help eliminate "works on my machine"
problem by providing logical separation for the runtime environment during the
development phase. That way you can gain portability across on-premises and cloud
environment.
27.
What is API Gateway?
API Gateway is a special class of microservices that meets the need of a single client
application (such as android app, web app, angular JS app, iPhone app, etc) and
provide it with single entry point to the backend resources (microservices), providing
each request, aggregating the response and transforming them to meet the client
application’s needs. Api Gateway can use a client-side load balancer library (Ribbon)
protocol translation i.e. HTTP to AMQP if necessary. It can handle security for
3. Path Rewriting
28.
How to achieve zero-downtime during the deployments?
where at any given point in time, at least one service will remain available to
customers.
Blue-green deployment
One way of achieving this is blue/green deployment. In this approach, two versions
of a single microservice are deployed at a time. But only one version is taking real
requests. Once the newer version is tested to the required satisfaction level, you can
You can run a smoke-test suite to verify that the functionality is running correctly in
the newly deployed version. Based on the results of smoke-test, newer version can
Lets say you have two instances of a service running at the same time, and both are
registered in Eureka registry. Further, both instances are deployed using two distinct
hostnames:
Lets say you have two instances of a service running at the same time, and both are registered
in Eureka registry. Further, both instances are deployed using two distinct hostnames:
/src/main/resources/application.yml
spring.application.name: ticketBooks-service
---
spring.profiles: blue
---
spring.profiles: green
Now the client app that needs to make api calls to books-service may look like below:
Now the client app that needs to make api calls to books-service may look like below:
@RestController
@SpringBootApplication
@EnableDiscoveryClient
public class ClientApp {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate(); }
@RequestMapping("/hit-some-api")
public Object hitSomeApi() {
return restTemplate().getForObject("https://ticketBooks-service/some-uri",
Object.class); }
down and delete its entry from Eureka registry. But these changes will not be reflected in the
ClientApp until it fetches the registry again (which happens every 30 seconds). So for upto 30
To fix this, we can use Spring Retry support in Ribbon client-side load balancer. To enable
compile("org.springframework.boot:spring-boot-starter-aop")
compile("org.springframework.retry:spring-retry")
below:
To fix this, we can use Spring Retry support in Ribbon client-side load balancer. To enable
compile("org.springframework.boot:spring-boot-starter-aop")
compile("org.springframework.retry:spring-retry")
below:
... }
Once this is done, Ribbon will automatically configure itself to use retry logic and any failed
(in round-robins fashion) by Ribbon. You can customize this behaviour using the below
properties:
/src/main/resources/application.yml
ribbon:
MaxAutoRetries: 5
MaxAutoRetriesNextServer: 5
OkToRetryOnAllOperations: true
OkToRetryOnAllErrors: true
29.
How to achieve zero-downtime deployment(blue/green) when there is a
database change?
The deployment scenario becomes complex when there are database changes
during the upgrade. There can be two different scenarios: 1. database change is
backward compatible (e.g. adding a new table column) 2. database change is not
compatible with an older version of the application (e.g. renaming an existing table
column)
be fully automated using Flyway. We can add the script to create a new
column and the script will be executed at the time of deployment. Now during
blue/green deployment, two versions of the application (say v1 and v2) will be
connected to the same database. We need to make sure that the newly added
columns allow null values (btw that’s part of the backward compatible
change). If everything goes well, then we can switch off the older version v1,
can create a new column fname and copy all existing values of first_name into
v1 to the new column (fname) manually after bringing down the v1. If the
30.
How to maintain ACID in microservice architecture?
Atomicity
In a transaction involving two or more entities, either all of the records are
Consistency
A database transaction must change affected data only in allowed ways following
Isolation
Any transaction in progress (not yet committed) must remain isolated from any other
transaction.
Durability
Committed records are saved by a database such that even in case of a failure or
database restart, the data is available in its correct state. Any transaction in progress
(not yet committed) must remain isolated from any other transaction.
Durability
Committed records are saved by a database such that even in case of a failure or database
compliance:
1. One way to achieve ACID compliance is to use a two-phase commit (a.k.a 2PC), which
ensures that all involved services must commit to transaction completion or all the
2 Phase Commit should ideally be discouraged in microservices architecture due to its fragile
and complex nature. We can achieve some level of ACID compliance in distributed systems
through eventual consistency and that should be the right approach to do it.