Apps & Microservices – What you need to know: Autonomy and the challenges you will face.
Tags: microservices, beginners, tutorial, dotnet
Published: 2018-05-31 12:37:58

---
title: Apps & Microservices – What you need to know: Autonomy and the challenges you will face.
published: true
description: Microservice based applications – What you need to know. Autonomy and the challenges you will face.
tags: Microservices, beginners, tutorial, dotnet
cover_image: https://thepracticaldev.s3.amazonaws.com/i/d85ifzq68r5vo4p9mg8u.png 
---
A lot of what I will be going through will reference this amazing 289 page behemoth document from Microsoft which can be downloaded from here:

<a href="https://aka.ms/microservicesebook">Architecture for containerized .Net applications</a>

I'll be linking to blog posts, videos, and any interesting whitepapers I have found. Whilst also looking into how others have created, or transformed previous monolithic applications into multiple loosely coupled micro services.

As with anything this large and all engrossing, this will cover my journey through this process and anything I have learnt. If you have any other suggestions or ideas about what is written then feel free to leave comments below and I can make changes where necessary.

So lets get onto it.
<h2>What are Microservices?</h2>
Well first we need to start with simply what is a service and what is a system?

A service is in software terms is:
<ul>
 	<li>owned, built, and run by an organisation</li>
 	<li>is responsible for holding, processing, and/ or distributing particular kinds of data within the scope of a system</li>
 	<li>can be built, deployed, and run independently, meeting defined operational objectives</li>
 	<li>communicates with consumers and other services, presenting information using conventions and/or contract assurances</li>
 	<li>handles failure conditions such that failures cannot lead to information corruption</li>
 	<li>protects itself against unwanted access, and its information against loss</li>
</ul>
A set of services compromise a system
<ul>
 	<li>A system is a group of services and systems, aiming to provide a combined solution for a well-defined scope.</li>
 	<li>A system may appear and act as a service towards other parties.</li>
 	<li>Systems may share services</li>
 	<li>Consumers may interact with multiple systems</li>
</ul>
A service is not a specific set of languages or frameworks, it is a combination of these services to deliver a solution. It is not simply an API in a docker instance sat on a Linux container written in .Net, JavaScript or any other scripting language. <strong>It is independent of implementation choices.</strong>

So what is the difference between a service and microservice? Well microservices must be independently deployable, whereas SOA <b>services</b> are often implemented in deployment monoliths. <a href="http://www.soapatterns.org/">SOA is an architectural pattern</a> in which application components provide <b>services</b> to other components. However, in SOA those components can belong to the same application.
<blockquote>
<h2 style="text-align: center;">The most important thing to remember with Microservices is that they're "<strong>Autonomous"</strong></h2>
</blockquote>
That means:
<ul>
 	<li>A service owns all of the state it immediately depends on and manages</li>
 	<li>A service owns its communication contract</li>
 	<li>A service can be changed, redeployed, and/or completely replaced</li>
 	<li>A service has a well-known set of communication paths</li>
 	<li>Services shall have no shared state with others</li>
 	<li>Don't depend on or assume any common data store</li>
 	<li>Don't depend on any shared in-memory state</li>
 	<li>No sideline communications between services</li>
 	<li>All communication is explicit</li>
</ul>
It all boils down to remembering that Autonomy is about cross organisational collaboration. It's ethos is that no single service is coupled to another!
<h2>Challenges and solutions for distributed data management</h2>
<h3>Defining Boundaries</h3>
The first challenge you will have when designing your microservice architecture is how to separate your current setup into autonomous chunks. You will need to define the boundaries of each microservice identifying decoupled data points and contexts within the same application. The goal is not to get the most granular separation possible, but the most meaningful separation needed for your domain, if you define a boundary and then find a high number of dependencies you will probably need to redefine again.
<blockquote><strong>The emphasis is not on size but on business capabilities.</strong></blockquote>
You should define your boundaries based on the Bounded Context pattern. In order to identify these a Domain Driven Design (DDD) <a href="https://www.infoq.com/articles/ddd-contextmapping">or Context Mapping</a> pattern can be used.
<h3>Consistency across multiple microservices</h3>
As each microservice is decoupled from others, it is a challenge to keep consistency of data across multiple microservices.

<img class=" size-full wp-image-873 aligncenter" src="http://blog.designpuddle.com/wp-content/uploads/2017/07/Conistency.png" alt="Conistency.PNG" width="498" height="284" />

We can see above that when the price changes in one microservice we will have to propagate that change to the others. Usually this would involve a join or an API call to reflect this, however with each microservice having a private database we need to use <strong>eventual consistency </strong>based on asynchronous communication such as integration events.
<h3>Distributed systems communication and data retrieval</h3>
With potentially many decouple microservices running separately, it is a challenge to to pick the right solution with regards to querying data from these microservices in an optimal fashion.

When reading online and using the PDF attached at the top of the page <strong>Api Gateways</strong> are mentioned heavily when creating microservices as a way of grouping them together. Although this can be an easy approach to take, it is fundamentally against the core principles of microservices.

Firstly I'll go through a quick history lesson on <strong>ESB</strong> (Enterprise Service Bus) and what this was, before talking about <strong>Api Gateways </strong>and how they are similar.
<h2>What is/was ESB (Enterprise Service Bus)</h2>
<img class=" aligncenter" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/ESB.svg/220px-ESB.svg.png" />
<blockquote><strong>The ESB Model promised simplification through centralization</strong></blockquote>
The entity service bus promised to make systems more simplified by have a central point dealing with everything, in smaller applications there are advantages to this pattern, however at scale many of the ESB advantages actually become its biggest weaknesses.

The ESB eventually becomes a bottleneck as it's tightly coupled to the every part of the system, the dilemma is at scale, with mobile clients, lots of services, nobody is owning the centralised area which would require a change every time one of these services are updated, upgraded or changed entirely, this could/would result in downtime, and affect the whole system!
<h2>What is an Api Gateway</h2>
An API gateway falls in to the same sort of trap. It sits centralised dealing with multiple microservices. Clearly it's not as large a behemoth as the ESB model, but changing microservice within the gateway would require changes in both the service and the gateway.

If they need to be used API Gateways should be segregated based on business boundaries and not act as an aggregator for the whole application.

<img class=" size-full wp-image-734 aligncenter" src="http://blog.designpuddle.com/wp-content/uploads/2017/07/ApiGateway.png" alt="ApiGateway.PNG" width="830" height="465" />
<h3>Drawbacks of the API Gateway pattern</h3>
<ul>
 	<li>The most important <strong>drawback</strong> is that when you implement an API Gateway, you are coupling that tier with the internal microservices. Coupling like this might introduce serious difficulties for your application. <strong>(The cloud architect Clemens Vaster refers to this potential difficulty as “the new ESB” in his "Messaging and Microservices" session from at GOTO 2016 that's shown below.)</strong></li>
 	<li>Using a microservices API Gateway creates an additional possible point of failure.</li>
 	<li>The API Gateway can represent a possible bottleneck if it is not scaled out properly</li>
 	<li>An API Gateway requires additional development cost and future maintenance if it includes custom logic and data aggregation. Developers must update the API Gateway in order to expose each microservice’s endpoints. Moreover, implementation changes in the internal microservices might cause code changes at the API Gateway level. However, if the API Gateway is just applying security, logging, and versioning (as when using Azure API Management), this additional development cost might not apply.</li>
</ul>
This great conference mentioned above from Clemens Vaser that talks about Microservices and how API Gateways are a bad idea. He documents how we can fall into the same trap that we did with ESB's and strongly argues against their use. I have also attached his slides from the presentation below in the Appendix.

https://www.youtube.com/watch?v=rXi5CLjIQ9k
<h2></h2>
In a monolithic application running on a single process, modules call one another using method or function calls. These can be strongly coupled using code such as new Class (), or can be loosely coupled by using Dependency Injection.

Either way, the objects are running within the same process. The biggest challenge when changing from a monolithic application to a microservices-based application lies in changing the communication mechanism.

A direct conversion from in-process method calls into Remote Process calls to services will cause an inefficient communication that will not perform well in distributed environments.

The challenges of designing a distributed system properly have been well documented; assumptions that are made by programmers can cause problems. These were penned by <a href="https://en.wikipedia.org/wiki/L_Peter_Deutsch">L Peter Deutsch</a> and consist of:
<ol>
 	<li>The network is reliable.</li>
 	<li>Latency is zero.</li>
 	<li>Bandwidth is infinite.</li>
 	<li>The network is secure.</li>
 	<li>Topology doesn't change.</li>
 	<li>There is one administrator.</li>
 	<li>Transport cost is zero.</li>
 	<li>The network is homogeneous.</li>
</ol>
Please be aware, non of these examples listed are true, you should not fall in the trap of thinking that any of these is not worth thinking about and that they will deal with themselves. Each of these require code coverage to handle, making sure the code can handle network outages, packet loss, changes to security protocols etc.

More can be read about these fallacies here: <a href="http://blog.fogcreek.com/eight-fallacies-of-distributed-computing-tech-talk/">8 fallacies of distributed systems</a>
<blockquote>There is not one solution, but several.</blockquote>
<h3></h3>
<h3>AMQP, HTTP or TCP</h3>
A microservices based application is a distributed system running on multiple processes or services, usually across multiple servers or hosts. Each service is typically a process. Therefore, services must interact using an inter-process communication protocol such as HTTP, AMQP, or a binary protocol like TCP, depending on the nature of each service.
<h3>Smart endpoints and dumb pipes</h3>
Is a term evocative of microservices and is a design principle that is tried and tested leveraging asynchronous communication mechanisms over complex system topology.

A design that is as decoupled as possible, choreographed by using <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">RESTFUL</a> and flexible event driven communications instead of a centralised orchestrator.

The two most common methods are using HTTP/S messages with API's. This is a synchronous protocol, where the clients sends a request and waits for a response. This would usually use a <a href="https://en.wikipedia.org/wiki/Command_pattern">Command Pattern</a> where each request is processed by one service.

<img class=" size-full wp-image-827 aligncenter" src="http://blog.designpuddle.com/wp-content/uploads/2017/07/RequestReponseComHTTP.png" alt="RequestReponseComHTTP.PNG" width="653" height="242" />

The other is lightweight asynchronous messaging protocols such as <a href="https://www.amqp.org/">AMQP</a>. Client code or messages don't need to wait for a response, simply sending the message to a broker such as <a href="https://www.rabbitmq.com/">RabbitMQ</a> where they then get handled by a separate process. The pub/sub approach is one such mechanism leveraging multiple receivers as the asynchronous nature means each request could be handled by one or more instances of services. The other is event driven communication usually implemented using a services bus with such options available as <a href="http://masstransit-project.com/">MassTransit</a>, <a href="https://particular.net/nservicebus">NServiceBus</a> using queues or Azure Service Bus by using topics and subscriptions.

<img class=" size-full wp-image-826 aligncenter" src="http://blog.designpuddle.com/wp-content/uploads/2017/07/AsynchronousEvents.png" alt="AsynchronousEvents" width="677" height="340" />

A comparison between these two approaches can be found here: <a href="https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-queues-topics-subscriptions">Queues vs Topics and Subscriptions.</a>
<h3>Communication between services</h3>
You should try to minimize the communication between your microservices.

The less communication between these, the better. Of course, sometimes you will have to integrate the microservices. The critical rule here is that the communications should be asynchronous and carried out by propagating data asynchronously, not depending on other internal microservices as part of the initial HTTP request/response.

You should never depend on synchronous communication between microservices, the goal is for each microservice to be autonomous and available to the client consumer, even if the other services that are part of the application are offline or corrupt. This means your architecture has to be resilient enough to handle when certain services fail

Synchronous operations, will mean performance is impacted. The more you add synchronous dependencies (like query requests) between microservices, the worse the overall response time will be at the client.
<h3>Microservice versioning, discovery and service registry</h3>
The benefits of the microservices model come at the cost of increased operational complexity, due to things like platform heterogeneity, the need for service discovery, and messaging and API call volumes.

A service API will need to change over time. When this happens, and especially when it's a public API being consumed by multiple applications you cannot force uptake to this new contract. A versioning strategy must be put in place to keep both old and new versions available to your users.

The <a href="https://en.wikipedia.org/wiki/Mediator_pattern">mediator</a> pattern can split your implementations into independent handlers, and <a href="https://www.infoq.com/articles/mark-baker-hypermedia">Hypermedia</a> is great for versioning your services.

A service registry is needed as your URLs of each microservice needs to be resolved, wherever it may be running. In the same way DNS resolves an address your services need a unique name to be discoverable too. The <a href="http://microservices.io/patterns/service-registry.html">service registry pattern</a> is key to keeping your endpoints and service instances up to date.

<hr />

<h2>Additional Resources</h2>
<a href="https://aka.ms/microservicesebook">Architecture for containerized .Net applications</a>

<a href="http://gotocon.com/dl/goto-amsterdam-2016/slides/ClemensVasters_MessagingAndMicroservices.pdf" target="_blank" rel="noopener">Messaging and Microservices - Clemens Vaster</a>