Microservices interview questions
50 questions, 49 with answers. 1,619 open jobs in India ask for Microservices.
What are the possible ways for communication between microservices?
- Synchronous protocol. HTTP is a synchronous protocol. The client sends a request and waits for a response from the service. That's independent of the client code execution that could be synchronous (thread is blocked) or asynchronous (thread isn't blocked, and the response will reach a callback eventually). The important point here is that the protocol (HTTP/HTTPS) is synchronous and the client code can only continue its task when it receives the HTTP server response.
- Asynchronous protocol. Other protocols like AMQP (a protocol supported by many operating systems and cloud environments) use asynchronous messages. The client code or message sender usually doesn't wait for a response. It just sends the message as when sending a message to a RabbitMQ queue or any other message broker. Links
- https://docs.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/communication-in-microservice-architecture
- https://dzone.com/articles/communication-between-microservices
From Java interview (MIT)
What is exchange in message queue?
Exchange: a queue aggregator that abstract away message queues and routes messages to the appropriate queue based on some predefined logic. Links
- https://dev.to/matteojoliveau/microservices-communications-why-you-should-switch-to-message-queues--48ia
From Java interview (MIT)
What are the benefits of microservices?
- Technology Heterogeneity
- Resilience
- Scaling
- Ease of Deployment
- Organizational Alignment
- Composability
- Optimizing for Replaceability Links
- https://stackoverflow.com/questions/34903605/microservices-what-are-pros-and-cons
- https://www.tiempodev.com/blog/disadvantages-of-a-microservices-architecture/
From Java interview (MIT)
What are the disadvantages of microservices?
- Microservices Are More Complex
- Microservices Require Cultural Changes
- Microservices Are More Expensive
- Microservices Pose Security Challenges Links https://www.tiempodev.com/blog/disadvantages-of-a-microservices-architecture/
From Java interview (MIT)
What are the possible issues in microservices?
- As if monitoring a monolith wasn’t hard enough
- Logging is distributed between services
- An issue that’s caused by one service, can cause trouble elsewhere
- Finding the root cause of problems
- Version management and cyclic dependencies between services Links
- https://blog.overops.com/5-ways-to-not-f-up-your-microservices-in-production/
From Java interview (MIT)
What are the possible solutions for the case when one service is not available?
- The circuit breaker pattern is the solution to this problem. The basic idea behind the circuit breaker is very simple. You wrap a protected function call in a circuit breaker object, which monitors for failures. Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error or with some alternative service or default message, without the protected call being made at all. This will make sure system is responsive and threads are not waiting for an unresponsive call.
- Retry Logic Links
- https://blog.risingstack.com/designing-microservices-architecture-for-failure/
- https://dzone.com/articles/circuit-breaker-pattern
From Java interview (MIT)
What is the difference between synchronous and asynchronous communication?
- Synchronous protocol. HTTP is a synchronous protocol. The client sends a request and waits for a response from the service. That's independent of the client code execution that could be synchronous (thread is blocked) or asynchronous (thread isn't blocked, and the response will reach a callback eventually). The important point here is that the protocol (HTTP/HTTPS) is synchronous and the client code can only continue its task when it receives the HTTP server response.
- Asynchronous protocol. Other protocols like AMQP (a protocol supported by many operating systems and cloud environments) use asynchronous messages. The client code or message sender usually doesn't wait for a response. It just sends the message as when sending a message to a RabbitMQ queue or any other message broker. Links https://docs.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/communication-in-microservice-architecture
From Java interview (MIT)
What are possible ways for implementing authentication in microservices?
- Distributed Session Management
- Client Token
- Single sign-on
- Client Token with API Gateway
- Third-party application access
- Mutual Authentication Links
- https://medium.com/tech-tajawal/microservice-authentication-and-authorization-solutions-e0e5e74b248a
- https://medium.com/@marcus.cavalcanti/stateless-authentication-for-microservices-9914c3529663
From Java interview (MIT)
What is Eventual consistency?
Rather than ensuring that the system is in a consistent state all the time, instead we can accept that the system will get it at some point in the future. This approach is especially useful for long-living business operations. Links
- https://softwareengineering.stackexchange.com/questions/354911/microservices-handling-eventual-consistency
From Java interview (MIT)
How different types of communication can influence on performance?
You should prefer asynchronous communication for all remote calls. They don’t block any resources while you’re waiting for the response and you can even execute multiple calls in parallel. That can provide huge performance improvements because you just need to wait until the slowest service answered your request.
As always, there are several ways to implement an asynchronous communication between two services. One of them is an asynchronous REST call. Links
- https://stackify.com/communication-microservices-avoid-common-problems/
From Java interview (MIT)
Difference between Microservices Architecture and SOA
I guess you could think of the Microservices Architectural Style as a specialisation of SOA. Don't forget that one of the accepted views is that all SOA really is, is four sentences:
- Boundaries are explicit
- Services are autonomous
- Services share schema and contract, not class
Service compatibility is based on policy
-Don Box, Microsoft (pre-.Net 3.0)
This brings us to the canonical definition of microservices, from Lewis/Fowler:
In short, the microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralised management of these services, which may be written in different programming languages and use different data storage technologies.
From this definition, it's clear that microservices fulfil at least the first two tenets (with a real emphasis on the second), but it's questionable whether they fulfil the third (I don't really understand tenet 4 so I won't comment).
The reason the third tenet may not hold for microservices is that one of the characteristics of microservices is that they are generally exposed over a RESTful API, which, one could argue, does not expose contract and schema at all (over and above the regular HTTP verbiage), as we see from Fowler:
a suite of small services, each... communicating with lightweight mechanisms, often an HTTP resource API
Another way in which a microservices style deviates from SOA is with this prescription:
These services are... independently deployable by fully automated deployment machinery
Following the original tenets of SOA does not prevent me from manually copying my service binaries into my production environment, but with the microservices approach, the service deployment and management should be fully automated.
From Stack Overflow: asked by TheCoder, answered by tom redfern (CC BY-SA 3.0)
API gateway vs. reverse proxy
It is easier to think about them if you realize they aren't mutually exclusive. Think of an API gateway as a specific type reverse proxy implementation.
In regards to your questions, it is not uncommon to see both used in conjunction where the API gateway is treated as an application tier that sits behind a reverse proxy for load balancing and health checking. An example would be something like a WAF sandwich architecture in that your Web Application Firewall/API Gateway is sandwiched by reverse proxy tiers, one for the WAF itself and the other for the individual microservices it talks to.
Regarding the differences, they are very similar. It's just nomenclature. As you take a basic reverse proxy setup and start bolting on more pieces like authentication, rate limiting, dynamic config updates, and service discovery, people are more likely to call that an API gateway.
From Stack Overflow: asked by user1459144, answered by Justin Talbott (CC BY-SA 4.0)
Where does Elixir/erlang fit into the microservices approach?
This is a very open question but I will try to illustrate why Elixir/Erlang may be the best platform out there for developing distributed systems (regardless if you are working with microservices).
First, let's start with some background. The Erlang VM and its standard library were designed upfront for building distributed systems and this really shows up. As far as I know, it is the only runtime and VM used widely in production designed upfront for this use case.
Applications
For example, you have already hinted at "applications". In Erlang/Elixir, code is packaged inside applications which:
- are started and stopped as unit. Starting and stopping your system is a matter of starting all applications in it
- provide a unified directory structure and configuration API (which is not XML!). If you have already worked with and configured an Open Telecom Platform (OTP) application, you know how to work with any other one
- contains your application supervision tree, with all processes (by process I mean "VM processes" which are lightweight threads of computation) and their state
The impact of this design is huge. It means that Elixir developers, when writing applications have a more explicit approach to:
- how their code is started and stopped
- what are the processes that make part of an application and therefore what is the application state
- how those process will react and be affected in case of crashes or when something goes wrong
Not only that, the tooling around this abstraction is great. If you have Elixir installed, open up "iex" and type:
:observer.start(). Besides showing information and graphs about your live system, you can kill random processes, see their memory usage, state and more. Here is an example of running this in a Phoenix application:The difference here is that Applications and Processes give you an abstraction to reason about your code in production. Many languages provides packages, objects and modules mostly for code organization with no reflection on the runtime system. If you have a class attribute or a singleton object: how can you reason about the entities that can manipulate it? If you have a memory leak or a bottleneck, how can you find the entity responsible for it?
If you ask anyone running a distributed system, that's the kind of insight that they want, and with Erlang/Elixir you have that as the building block.
Communication
All of this is just the beginning really. When building a distributed system, you need to choose a communication protocol and the data serializer. A lot of people choose HTTP and JSON which, when you think about it, is a very verbose and expensive combination for performing what is really RPC calls.
With Erlang/Elixir, you already have a communication protocol and a serialization mechanism out of the box. If you want to have two machines communicating with each other, you only need to give them names, ensure they have the same secret, and you are done.
Jamie talked about this at Erlang Factory 2015 and how they were able to leverage this to build a game platform: https://www.youtube.com/watch?v=_i6n-eWiVn4
If you want to use HTTP and JSON, that is fine too and libraries like Plug and frameworks like Phoenix will guarantee you are productive here too.
Microservices
So far I haven't talked about microservices. That's because, up to this point, they don't really matter. You are already designing your system and nodes around very tiny processes that are isolated. Call them nanoservices if you'd like to!
Not only that, they are also packaged into applications, which group them as entities that can be started and stopped as unit. If you have applications A, B and C, and then you want to deploy them as [A, B] + [C] or [A] + [B] + [C], you will have very little trouble in doing so due to their inherent design. Or, even better, if you want to avoid adding the complexity of microservices deployments into your system upfront, you can just deploy them altogether in the same node.
Read the rest at the sourceFrom Stack Overflow: asked by Papipo, answered by José Valim (CC BY-SA 4.0)
Microservices vs Monolithic Architecture
This is a very important question because a few people get lured by all the buzz around microservices, and there are tradeoffs to consider. So, what are the benefits and challenges of microservices (when compared with the monolithic model)?
Benefits
- Deployability: more agility to roll out new versions of a service due to shorter build+test+deploy cycles. Also, flexibility to employ service-specific security, replication, persistence, and monitoring configurations.
- Reliability: a microservice fault affects that microservice alone and its consumers, whereas in the monolithic model a service fault may bring down the entire monolith.
- Availability: rolling out a new version of a microservice requires little downtime, whereas rolling out a new version of a service in the monolith requires a typically slower restart of the entire monolith.
- Scalability: each microservice can be scaled independently using pools, clusters, grids. The deployment characteristics make microservices a great match for the elasticity of the cloud.
- Modifiability: more flexibility to use new frameworks, libraries, datasources, and other resources. Also, microservices are loosely-coupled, modular components only accessible via their contracts, and hence less prone to turn into a big ball of mud.
- Management: the application development effort is divided across teams that are smaller and work more independently.
- Design autonomy: the team has freedom to employ different technologies, frameworks, and patterns to design and implement each microservice, and can change and redeploy each microservice independently
Challenges
- Deployability: there are far more deployment units, so there are more complex jobs, scripts, transfer areas, and config files to oversee for deployment. (For that reason, continuous delivery and DevOps are highly desirable for microservice projects.)
- Performance: services more likely need to communicate over the network, whereas services within the monolith may benefit from local calls. (For that reason, the design should avoid "chatty" microservices.)
- Modifiability: changes to the contract are more likely to impact consumers deployed elsewhere, whereas in the monolithic model consumers are more likely to be within the monolith and will be rolled out in lockstep with the service. Also, mechanisms to improve autonomy, such as eventual consistency and asynchronous calls, add complexity to microservices.
- Testability: integration tests are harder to setup and run because they may span different microservices on different runtime environments.
- Management: the effort to manage operations increases because there are more runtime components, log files, and point-to-point interactions to oversee.
- Memory use: several classes and libraries are often replicated in each microservice bundle and the overall memory footprint increases.
- Runtime autonomy: in the monolith the overall business logic is collocated. With microservices the logic is spread across microservices. So, all else being equal, it's more likely that a microservice will interact with other microservices over the network--that interaction decreases autonomy. If the interaction between microservices involves changing data, the need for a transactional boundary further compromises autonomy. The good news is that to avoid runtime autonomy issues, we can employ techniques such as eventual consistency, event-driven architecture, CQRS, cache (data replication), and aligning microservices with DDD bounded contexts. These techniques are not inherent to microservices, but have been suggested by virtually every author I've read.
Read the rest at the sourceFrom Stack Overflow: asked by user902383, answered by Paulo Merson (CC BY-SA 4.0)
Kafka Msg VS REST Calls
Gist (for those who want just the gist)
-
Kafka - Publish & Subscribe (just process the pipeline, will notify once the job is done)
REST - Request & Await response (on-demand)
-
Kafka - Publish once - Subscribe n times (by n components).
REST - Request once, get the response once. Deal over.
-
Kafka - Data is stored in topic. Seek back & forth (offsets) whenever you want till the topic is retained.
REST - Once the response is over, it is over. Manually employ a database to store the processed data.
-
Kafka - Split the processing, have intermediate data stored in intermediate topics (for speed and fault-tolerance)
REST - Take the data, process it all at once OR if you wish to break it down, don't forget to take care of your OWN intermediate data stores.
-
Kafka - The one who makes the request typically is not interested in a response (except the response that if the message is sent)
REST - I am making the request means I typically expect a response (not just a response that you have received the request, but something that is meaningful to me, some computed result for example!)
Q&A style
Is your data streaming?
If the data keeps on coming and you have a pipeline to execute, Kafka is best.Do you need a request-response model?
If the user requests for something and they wait for a response, then REST is best. Though, you can still use Kafka for this, such asspring-kafkaReplyingKafkaTemplate.Kafka (or any other streaming platform) is typically used for pipelines, i.e. where we have forward flow of data. LinkedIn built Kafka to centrally collect log and metrics into their data warehouse.
Data comes to Kafka and from there it goes through component1, component2 and so on and finally (typically) lands in a database / datalake for long-term storage. Or you can can keep data in Kafka forever like the New York Times.
To get the information on-demand we need a data store (a database) where we can query and get it. In such a case we provide a REST interface which the user can invoke and get the data they want. Confluent, for example, also has a REST Proxy for Kafka to use HTTP to request topic information, however, it is a scan, not an indexed lookup like a database would offer.
Regarding your example,
Everyday vendor service calls the vendor API to get new items and these need to be moved into inventory service
Questions & Answers
Is your vendor API using REST?
Then you need to pull the data and push to Kafka. From there your inventory service (or any other service thereafter) will subscribe to that topic and execute their processing logic.
The advantage here is that you can add any other service which requires vendor data as a consumer to the vendor topic.
Moreover, the vendor data is always there for you even after your inventory service processed it.
If you use REST for this, you need to call the Vendor API for every component that requires vendor data which becomes trivial when used with Kafka
Do you want the inventory to be queried?
Store it in a database after processing through Kafka and provide a REST on top of this. This is needed because Kafka is typically a log, to make the data query-able you would need some database.
From Comments
Compare kafka vs reactive rest api
Read the rest at the sourceFrom Stack Overflow: asked by user1955934, answered by JavaTechnical (CC BY-SA 4.0)
-
Protocol Buffer vs Json - when to choose one over the other?
When to use JSON, copied from here:
- You need or want data to be human readable
- Data from the service is directly consumed by a web browser
- Your server side application is written in JavaScript
- You aren’t prepared to tie the data model to a schema
- You don’t have the bandwidth to add another tool to your arsenal
- The operational burden of running a different kind of network service is too great
Advantages of ProtoBuf, copied from here:
- Guarantees type-safety
- Prevents schema-violations
- Gives you simple accessors
- Fast serialization/deserialization
- Backward compatibility
While we are at it, have you looked at flatbuffers, which that article also mentions?
Some of the aspects are covered here google protocol buffers vs json vs XML
From Stack Overflow: asked by Kaidul, answered by so-random-dude (CC BY-SA 4.0)
How does data denormalization work with the Microservice Pattern?
This is subjective but the following solution worked for me, my team, and our DB team.
- At the application layer, Microservices are decomposed to semantic function.
- e.g. a
Contactservice might CRUD contacts (metadata about contacts: names, phone numbers, contact info, etc.) - e.g. a
Userservice might CRUD users with login credentials, authorization roles, etc. - e.g. a
Paymentservice might CRUD payments and work under the hood with a 3rd party PCI compliant service like Stripe, etc.
- e.g. a
- At the DB layer, the tables can be organized however the devs/DBs/devops people want the tables organized
The problem is with cascading and service boundaries: Payments might need a User to know who is making a payment. Instead of modeling your services like this:
interface PaymentService { PaymentInfo makePayment(User user, Payment payment); }Model it like so:
interface PaymentService { PaymentInfo makePayment(Long userId, Payment payment); }This way, entities that belong to other microservices only are referenced inside a particular service by ID, not by object reference. This allows DB tables to have foreign keys all over the place, but at the app layer "foreign" entities (that is, entities living in other services) are available via ID. This stops object cascading from growing out of control and cleanly delineates service boundaries.
The problem it does incur is that it requires more network calls. For instance, if I gave each
Paymententity aUserreference, I could get the user for a particular payment with a single call:User user = paymentService.getUserForPayment(payment);But using what I'm suggesting here, you'll need two calls:
Long userId = paymentService.getPayment(payment).getUserId(); User user = userService.getUserById(userId);This may be a deal breaker. But if you're smart and implement caching, and implement well engineered microservices that respond in 50 - 100 ms each call, I have no doubt that these extra network calls can be crafted to not incur latency to the application.
From Stack Overflow: asked by smeeb, answered by smeeb (CC BY-SA 3.0)
- At the application layer, Microservices are decomposed to semantic function.
2PC vs Sagas (distributed transactions)
In my understanding (not a big user of 2PC since I consider it limiting):
- Typically, 2PC is for immediate transactions.
- Typically, Sagas are for long running transactions.
Use cases are obvious afterwards:
- 2PC can allow you to commit the whole transaction in a request or so, spanning this request across systems and networks. Assuming each participating system and network follows the protocol, you can commit or rollback the entire transaction seamlessly.
- Saga allows you split transaction into multiple steps, spanning long periods of times (not necessarily systems and networks).
Example:
- 2PC: Save Customer for every received Invoice request, while both are managed by 2 different systems.
- Sagas: Book a flight itinerary consisting of several connecting flights, while each individual flight is operated by different airlines.
I personally consider Saga capable of doing what 2PC can do. Opposite is not accurate.
I think Sagas are universal, while 2PC involves platform/vendor lockdown.
Updates/Additions (optional read):
My answer has been here for a while, and I see that the topic has gained some traction since.
I want to clarify a couple of points on this topic for those who come here and are not sure which route to take.
- Saga is a domain modeling (i.e., technology-agnostic) concept, while 2PC is a technology-specific notion with some (maybe many) vendors implementing it. For an analogy, it's the same if we compare the domain events (bare objects) with message brokers (such as RabbitMQ for example).
- 2PC can be a good choice if you are anyway married to platforms that implement such a protocol. Not all do, and thus I call this a limitation. I see that people found an argument that Saga is more limiting because it's harder to implement, but that's like saying orange is juicier than apple is sweet. Two different things.
- Consider the human factor too. Some people (developers, architects) are technology geeks. They call business logic or domain model a boilerplate code. I belong to another group of people who consider the domain model the most valuable piece of code. Such a preference also affects decisions between Saga and 2PC, as well as who likes what. I can't explain why you should prefer domain-driven thinking over technology-driven solutions because it won't fit on this page and you will abandon reading my answer. Please find more online, maybe through my writings.
@freakish in the comments mentioned a fair point: 2PC prefers consistency, while Saga degrades it to "eventual consistency." If you have a situation where consistency is more important than availability (please read CAP), then maybe you do need a system transaction protocol like 2PC. Otherwise, I recommend going with business transactions such as Saga. Please read System Transactions vs Business Transactions e.g. in PEAA.
From Stack Overflow: asked by Tuomas Toivonen, answered by Tengiz (CC BY-SA 4.0)
What is Upstream and Downstream services in a microservices based architecture?
Definition 1: The direction of action
Upstream: receiving requests from / sending responses to
- A service upstream is calling me.
Downstream: making requests to / receiving responses from
- I am calling a service downstream.
Definition 2: The direction of dependency
Upstream: making requests to / receiving responses from
- I am calling a service upstream.
Downstream: receiving requests from / sending responses to
- A service downstream is calling me.
So,
There are resources on the internet which support both of these definitions. Maybe we will resolve this question one day, but for now the answer is: it's either.
From Stack Overflow: asked by Shubham Tiwari, answered by tom redfern (CC BY-SA 4.0)
REST vs gRPC: when should I choose one over the other?
When done correctly, REST improves long-term evolvability and scalability at the cost of performance and added complexity. REST is ideal for services that must be developed and maintained independently, like the Web itself. Client and server can be loosely coupled and change without breaking each other.
RPC services can be simpler and perform better, at the cost of flexibility and independence. RPC services are ideal for circumstances where client and server are tightly coupled and follow the same development cycle.
However, most so-called REST services don't really follow REST at all, because REST became just a buzzword for any kind of HTTP API. In fact, most so-called REST APIs are so tightly coupled, they offer no advantage over an RPC design.
Given that, my somewhat cynical answers to your question are:
Some people are adopting gRPC for the same reason they adopted REST a few years ago: design-by-buzzword.
Many people are realizing the way they implement REST amounts to RPC anyway, so why not go with an standardized RPC framework and implement it correctly, instead of insisting on poor REST implementations?
REST is a solution for problems that appear in projects that span several organizations and have long-term goals. Maybe people are realizing they don't really need REST and looking for better options.
From Stack Overflow: asked by nmurthy, answered by Pedro Werneck (CC BY-SA 4.0)
What is service discovery, and why do you need it?
Let's start by reviewing what service-discovery is - here's a good explanation: https://www.nginx.com/blog/service-discovery-in-a-microservices-architecture/ (this link should pretty much clarify the issue asked)
And here's an example how it is used in practice: Suppose you have service B which is used by service A. Service B (like most services in SOA) is actually a cluster of applications of type B. Service A requires to use one of the nodes of cluster B, yet the cluster of B nodes is dynamic. i.e. B nodes are created and terminated, depending on the load on the overall B service. Now, we would like service A to communicate with a live B node every time it needs to use service B. In order to do so, we will use the service-discovery tool to provide us, at any given time, an address of one of the live B nodes.
So, trying to answer your above questions, putting the end-point server information (specifically endpoint address) as static configuration in a config file which is read at the startup of service A, won't give you the dynamics you'd like when service B endpoints may constantly change.
From Stack Overflow: asked by gesgsklw, answered by S. D. (CC BY-SA 3.0)
Should I use forever/pm2 within a (Docker) container?
My take is do not use an in-container process supervisor (forever, pm2) and instead use docker restart policy via the
--restart=always(or one of the other flavors of that option). This is more inline with the overall docker philosophy, and should operate very similarly to in-container process supervision since docker containers start running very quickly.The strongest advocate for running in-container process supervision I've seen is in the phusion baseimage-docker README if you want to explore the other position on this topic.
From Stack Overflow: asked by Patrick, answered by Peter Lyons (CC BY-SA 3.0)
What is the role of Zookeeper vs Eureka for microservices?
I am going to implement the orchestration of a set of microservices in my application.
This is a hard problem to solve by yourself. You are probably better off using an existing orchestration system (see below).
Is there any other powerful tool?
You should look into kubernetes, which seems to be the standard in orchestration these days. It has many additional benefits (enable scalability, self-healing, etc) and is widely used in production today. See the following links:
Regarding comparing zookeeper, eureka and kubernetes:
- Zookeeper is a distributed key value store. It can be used as the basis to implement service discovery (similar to etcd).
- Eureka is primarily a service locator used as part of Netflixes load balancers and failover(allow finding the right service targets for distributing client calls to members of an application cluster).
- Kubernetes is a container orchestration solution that includes the deployment, discovery and self-healing of services. For a complete list of features, check the link above. The service discovery in kubernetes is based on dns in the virtual network it spans and builds upon etcd.
- Consul (mentioned in the other answer) is a service discovery framework with a REST interface and some additional features (Health Checking, Service Segmentation,..). It has its own internal distributed key value store that can be used as well.
From Stack Overflow: asked by Supun Wijerathne, answered by Oswin Noetzelmann (CC BY-SA 4.0)
What is a microservice architecture?
Microservices in my own, hopefully simple terms
Monoliths
Traditionally web applications are big. You write one piece of software that runs on a server and answers requests in form of HTML, XML or JSON. If you want your web application to do something new, you add that functionality to the existing application. Such big systems are called "monolithic" (a monolith is a very big rock).
Monoliths are problematic, because they usually grow in size and complexity over time. This is a problem when developing something in a team. Developers are adding new code to the system and can't change or re-use the existing code, because there is many dependencies between the code pieces. They are also too afraid of removing old code because it might be used somewhere.
When delivering such code to clients, e.g. by putting it on the internet, we call that "deploying". Deploying and the usual testing after deployment is difficult, because within a big system there is a lot of things that can break. Finding out what is going wrong and who should fix it, is very difficult and requires people to know the whole thing.
Another disadvantage is the scalability. By that we mean "how can we serve more users at the same time?" A single web server computer can only handle a certain amount of users accessing it in parallel. Upgrading that computer to better hardware makes it serve more users, but you will soon hit the boundaries of what is possible with hardware. This upgrading is called vertical scaling. We could also put our web application on two or more servers, so that we can handle more users. This is called horizontal scaling. Monolithic applications are traditionally made only with vertical scaling in mind.
Microservices
In order to simplify the workflow with big applications, we can split it into smaller parts. Each part serves one particular purpose. We call that a "(web) service". These web services are very flexible to use. You can use them from within your existing monolithic application, either in the server part, or in the client part. You can also have web services that use other web services.
The split into single web services allows you to loosely couple your application. This means that as a user of the service you only depend on the service being up, available and working. You no longer need to take care of its dependencies, its compilation, deployment or testing. (There are even ways of decoupling further through events on queues, or on a bus.)
You can give that responsibility (of testing, compiling, deploying) to a different developer or team. You can't break their web service because you do not access it through the source code. They can even use a different programming language and you could still use their service.
This independence is made possible by deciding on using a common format and common protocols (a protocol is a way of communicating). For web services the most popular formats are JSON and XML. The protocol used the most is HTTP, because it's simple, well-supported by all existing software and your browser is using it, too.
The word "micro" in "microservices" just emphasises the idea to make these web services as small as possible. If you need a more complex service, it is usually better to create a new service that depends on one or more others. How to slice your application into services will depend on the domain, and on the data each service should hold.
When to use which?
Use Microservices if:
- you expect many people to work on the system in the long run (loosely coupled)
- you need to scale to millions of concurrent users (horizontally scaled)
- you need a highly available system with redundancy (modularised)
Monolithic applications are not old-school or outdated! They have plenty of advantages over Microservices in certain scenarios. Use them when:
Read the rest at the sourceFrom Stack Overflow: asked by Konrad, answered by Hugo G (CC BY-SA 4.0)
Which HTTP errors should never trigger an automatic retry?
There are some errors that should not be retried because they seem permanent:
- 400 Bad Request
- 401 Unauthorized
- 402 Payment Required
- 403 Forbidden
- 405 Method Not Allowed
- 406 Not Acceptable
- 407 Proxy Authentication Required
- 409 Conflict - it depends
- 410 Gone
- 411 Length Required
- 412 Precondition Failed
- 413 Payload Too Large
- 414 URI Too Long
- 415 Unsupported Media Type
- 416 Range Not Satisfiable
- 417 Expectation Failed
- 418 I'm a teapot - not sure about this one
- 421 Misdirected Request
- 422 Unprocessable Entity
- 423 Locked - it depends on how long a resource is locked in average (?)
- 424 Failed Dependency
- 426 Upgrade Required - can the client be upgraded automatically?
- 428 Precondition Required - I don't thing that the precondition can be fulfiled the second time without retring from the beginning of the whole process but it depends
- 429 Too Many Requests - it depends but it should not be retried to fast
- 431 Request Header Fields TooLarge
- 451 Unavailable For Legal Reasons
So, most of the 4** Client errors should not be retried.
The 5** Servers errors that should not be retried:
- 500 Internal Server Error - it depends on the cause of the error
- 501 Not Implemented
- 502 Bad Gateway - I saw used for temporary errors so it depends
- 505 HTTP Version Not Supported
- 506 Variant Also Negotiates
- 507 Insufficient Storage
- 508 Loop Detected
- 510 Not Extended
- 511 Network Authentication Required
However, in order to make the microservices more resilient you should use the Circuit breaker pattern and fail fast when the upstream is down.
From Stack Overflow: asked by cahen, answered by Constantin Galbenu (CC BY-SA 4.0)
Decompose microservices: Business capability vs Domain
The commenters are right - there are some subjective definitions at play here. But there are some principles and concepts that can help reason about the different approaches.
Conway's Law
It's not strictly the original definition, but I think the distinction can be better understood with reference to Conway's Law:
Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization's communication structure.
The Inverse Conway Manouvre
Following from that thinking, the Inverse Conway Maneuver evolved:
The 'Inverse Conway Maneuver' recommends evolving your team and organizational structure to promote your desired architecture. Ideally your technology architecture will display isomorphism with your business architecture.
The Inverse Conway Maneuver is an attempt to structure your organisation to harness Conway's Law to achieve a better system design.
Decomposition By Business Capability
With an understanding of these concepts, we can consider decomposition by Business Capability to be guiding the system design according to the way the business is structured. This echos Conway's law.
The pro of this approach is it helps to ensure alignment between development teams and business structural units. The con is it may bake business inefficiencies that arose before an automated system was considered, into the design of your system.
Decomposition By Domain
Domain Driven Design (DDD) provides a suite of tools and methodologies to reason about the underlying domain at hand, to reflect the best available understanding of the domain in the software design and to evolve the software design as understanding of the domain grows and changes. DDD Strategic Patterns guide the creation of a Context Map which can form the foundation of your microservices decomposition.
From this, we can consider decomposition by Domain to be guiding the system design according to an analysis of the processes and information flows .
The pro of this approach is that it can lead to a system design that closely models the reality of what is happening (or needs to happen). Hopefully the business structure already aligns with this - but where it doesn't, it can reveal inefficiencies in the existing business organisational structure.
If you have influence over the organisational structure, this can be a foundation for utilising the Inverse Conway Maneuver and to allow you to evolve the software, the dev teams and the business units to achieve alignment.
If you don't, you may end up introducing friction points where the system design becomes misaligned with the business capabilities.
Conclusion
The reality is, neither approach is mutually exclusive - you will probably end up with a compromise that attempts to balance alignment with business capabilities as they are already understood and problem domains as they are revealed through a DDD process.
From Stack Overflow: asked by necroface, answered by Chris Simon (CC BY-SA 3.0)
Single database vs multiple databases - Microservices Architecture
You can use a single shared database with tables that owned by different microservices if your data is heavily related. Also in case you have strong requirements on data consistency and availiblty of a service. There is pros and cons.
Pros
Reliability
- You can have totally consistent incremental backup of the entire system without downtime with standard DB tools.
- In case of event-driven architecture you can store events with your data. If you store events in DB you can even lose your broker and survive without data loss.
- Fully constrained and correct data relations.
Maintenance:
- You don't have to write network interfaces to fetch data from another service, but you can if you want that level of separation!
- No data duplication and stale states.
Features:
- Complex queries are possible and damn fast!
- Transactions are not so hard. (Retries are still required).
Cons
Reliability:
- Another single point of failure(In simple case). You can use a replicated setup for HA, but it requires OPS resources.
Maintenance:
- Schema changes(migrations) should be made very carefully(as external API changes) even with single writer principle implemented because schema missmatch on read is also a permanent failure. With big project its hard to track who will be affected by table change.
Discipline:
- Only owner of table can perform write operations on it.
- You still need to push hard to decouple your data to lower rate of transactional conflicts.
Performance:
- It hard to scale in terms of storage capacity and performance. There is a clustering solutions in almost any mature DB but as ia said above it requires much of OPS resources
Hate:
- Everyone will hate you for no reason when you'll say that you designed your microservices to use single database. Bear with it.
Other thoughts:
In my personal expirience single database is a good choice if you're not a Netflix and your application can not tolerate any form of data loss.
- "Shared database" is actually described as "Architecture pattern" on microservices.io with it's own pros and cons. So why put "anti" label on it?
- This and this articles give the opposite point of view on shared database pattern. Which totally makes sense from my point of view.
- This document describes the BAC theorem. It basically means that you can't have a full uptime AND consistent backup at the same time if you use multiple data storages.
From Stack Overflow: asked by Danyal Sandeelo, answered by Eduard Gan (CC BY-SA 4.0)
How does Ballerina differ from other languages?
- Is Ballerina an interpreted language?
Ballerina is a compiled programming language. It compiles to a platform-neutral binary form which is then interpreted by the Ballerina runtime.
- How to build Ballerina programs? Do we need to set Ballerina Home or any other system variables?
There is no system variable concept when it comes to Ballerina. Download and install the OS-specific installer from https://ballerina.io/downloads/
Running Ballerina programs
Use
ballerina runcommand to compile and run Ballerina programs.$ ballerina run hello.bal Hello, World!Use
ballerina buildcommand to produce a statically-linked executable binary with the extension "balx". Then useballerina runcommand to run the program.$ ballerina build hello.bal $ ls hello.bal hello.balx $ ballerina run hello.balx Hello, World!- How Ballerina supports dependency management? Are there any recommended build tools?
A Ballerina program usually consists of multiple Ballerina packages. A package is a collection of source files. It defines a namespace and the symbols in all the source files in the package belong to that namespace. If you want to refer to a symbol defined in another package, you need to first import that package, then you can refer to the symbol with the package name.
When you want to execute or build a Ballerina program, Ballerina resolves all your import packages using your program directory, built-in repository (Ballerina distribution contains all the core library package as well as some third-party connector packages ), or the Ballerina repository directory. Ballerina repository is the local repository available in your machine.
We will develop tools for you to manage the Ballerina repository in the future.
From Stack Overflow: asked by Abimaran Kugathasan, answered by Sameera Jayasoma (CC BY-SA 4.0)
Transactions across REST microservices?
What doesn't make sense:
- distributed transactions with REST services. REST services by definition are stateless, so they should not be participants in a transactional boundary that spans more than one service. Your user registration use case scenario makes sense, but the design with REST microservices to create User and Wallet data is not good.
What will give you headaches:
- EJBs with distributed transactions. It's one of those things that work in theory but not in practice. Right now I'm trying to make a distributed transaction work for remote EJBs across JBoss EAP 6.3 instances. We've been talking to RedHat support for weeks, and it didn't work yet.
- Two-phase commit solutions in general. I think the 2PC protocol is a great algorithm (many years ago I implemented it in C with RPC). It requires comprehensive fail recovery mechanisms, with retries, state repository, etc. All the complexity is hidden within the transaction framework (ex.: JBoss Arjuna). However, 2PC is not fail proof. There are situations the transaction simply can't complete. Then you need to identify and fix database inconsistencies manually. It may happen once in a million transactions if you're lucky, but it may happen once in every 100 transactions depending on your platform and scenario.
- Sagas (Compensating transactions). There's the implementation overhead of creating the compensating operations, and the coordination mechanism to activate compensation at the end. But compensation is not fail proof either. You may still end up with inconsistencies (= some headache).
What's probably the best alternative:
- Eventual consistency. Neither ACID-like distributed transactions nor compensating transactions are fail proof, and both may lead to inconsistencies. Eventual consistency is often better than "occasional inconsistency". There are different design solutions, such as:
- You may create a more robust solution using asynchronous communication. In your scenario, when Bob registers, the API gateway could send a message to a NewUser queue, and right-away reply to the user saying "You'll receive an email to confirm the account creation." A queue consumer service could process the message, perform the database changes in a single transaction, and send the email to Bob to notify the account creation.
- The User microservice creates the user record and a wallet record in the same database. In this case, the wallet store in the User microservice is a replica of the master wallet store only visible to the Wallet microservice. There's a data synchronization mechanism that is trigger-based or kicks in periodically to send data changes (e.g., new wallets) from the replica to the master, and vice-versa.
But what if you need synchronous responses?
- Remodel the microservices. If the solution with the queue doesn't work because the service consumer needs a response right away, then I'd rather remodel the User and Wallet functionality to be collocated in the same service (or at least in the same VM to avoid distributed transactions). Yes, it's a step farther from microservices and closer to a monolith, but will save you from some headache.
From Stack Overflow: asked by Olivier Lalonde, answered by Paulo Merson (CC BY-SA 4.0)
Orchestrating microservices
The Book Building Microservices describes in detail the styles mentioned by @RogerAlsing in his answer.
On page 43 under Orchestration vs Choreography the book says:
As we start to model more and more complex logic, we have to deal with the problem of managing business processes that stretch across the boundary of individual services. And with microservices, we’ll hit this limit sooner than usual. [...] When it comes to actually implementing this flow, there are two styles of architecture we could follow. With orchestration, we rely on a central brain to guide and drive the process, much like the conductor in an orchestra. With choreography, we inform each part of the system of its job and let it work out the details, like dancers all find‐ ing their way and reacting to others around them in a ballet.
The book then proceeds to explain the two styles. The orchestration style corresponds more to the SOA idea of orchestration/task services, whereas the choreography style corresponds to the dumb pipes and smart endpoints mentioned in Martin Fowler's article.
Orchestration Style
Under this style, the book above mentions:
Let’s think about what an orchestration solution would look like for this flow. Here, probably the simplest thing to do would be to have our customer service act as the central brain. On creation, it talks to the loyalty points bank, email service, and postal service [...], through a series of request/response calls. The customer service itself can then track where a customer is in this process. It can check to see if the customer’s account has been set up, or the email sent, or the post delivered. We get to take the flowchart [...] and model it directly into code. We could even use tooling that implements this for us, perhaps using an appropriate rules engine. Commercial tools exist for this very purpose in the form of business process modeling software. Assuming we use synchronous request/response, we could even know if each stage has worked [...] The downside to this orchestration approach is that the customer service can become too much of a central governing authority. It can become the hub in the middle of a web and a central point where logic starts to live. I have seen this approach result in a small number of smart “god” services telling anemic CRUD-based services what to do.
Note: I suppose that when the author mentions tooling he's referring to something like BPM (e.g. Activity, Apache ODE, Camunda). As a matter of fact, the Workflow Patterns Website has an awesome set of patterns to do this kind of orchestration and it also offers evaluation details of different vendor tools that help to implement it this way. I don't think the author implies one is required to use one of these tools to implement this style of integration though, other lightweight orchestration frameworks could be used e.g. Spring Integration, Apache Camel or Mule ESB
Read the rest at the sourceFrom Stack Overflow: asked by Roger Johansson, answered by Edwin Dalorzo (CC BY-SA 4.0)
After the last page: 1 question more, without answers. Go to the last page
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Java interviewby Anton LiauchukMIT, © 2020 Anton Liauchuk11 questions
- Stack Overflowby its contributors, named on each answerCC BY-SA22 questions
- Software Engineering Stack Exchangeby its contributors, named on each answerCC BY-SA17 questions