Building Microservices with .NET Core 2.0 - Second Edition - Gaurav Aroraa - E-Book

Building Microservices with .NET Core 2.0 - Second Edition E-Book

Gaurav Aroraa

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Architect your .NET applications by breaking them into really small pieces - microservices -using this practical, example-based guide.

About This Book

  • Start your microservices journey and get a broader perspective on microservices development using C# 7.0 with .NET Core 2.0
  • Build, deploy, and test microservices using ASP.Net Core, ASP.NET Core API, and Microsoft Azure Cloud
  • Get the basics of reactive microservices

Who This Book Is For

This book is for .NET Core developers who want to learn and understand the microservices architecture and implement it in their .NET Core applications. It's ideal for developers who are completely new to microservices or just have a theoretical understanding of this architectural approach and want to gain a practical perspective in order to better manage application complexities.

What You Will Learn

  • Get acquainted with Microsoft Azure Service Fabric
  • Compare microservices with monolithic applications and SOA
  • Learn Docker and Azure API management
  • Define a service interface and implement APIs using ASP.NET Core 2.0
  • Integrate services using a synchronous approach via RESTful APIs with ASP.NET Core 2.0
  • Implement microservices security using Azure Active Directory, OpenID Connect, and OAuth 2.0
  • Understand the operation and scaling of microservices in .NET Core 2.0
  • Understand the key features of reactive microservices and implement them using reactive extensions

In Detail

The microservices architectural style promotes the development of complex applications as a suite of small services based on business capabilities. This book will help you identify the appropriate service boundaries within your business. We'll start by looking at what microservices are and their main characteristics.

Moving forward, you will be introduced to real-life application scenarios; after assessing the current issues, we will begin the journey of transforming this application by splitting it into a suite of microservices using C# 7.0 with .NET Core 2.0. You will identify service boundaries, split the application into multiple microservices, and define service contracts. You will find out how to configure, deploy, and monitor microservices, and configure scaling to allow the application to quickly adapt to increased demand in the future.

With an introduction to reactive microservices, you'll strategically gain further value to keep your code base simple, focusing on what is more important rather than on messy asynchronous calls.

Style and approach

This guide serves as a stepping stone that helps .NET Core developers in their microservices architecture. This book provides just enough theory to understand the concepts and apply the examples.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 326

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Building Microservices with .NET Core 2.0

Second Edition

 

 

 

 

 

 

 

 

Transitioning monolithic architectures using microservices with .NET Core 2.0 using C# 7.0

 

 

 

 

 

 

 

 

Gaurav Aroraa

BIRMINGHAM - MUMBAI

Building Microservices with .NET Core 2.0

Second Edition

Copyright © 2017 Packt Publishing

 

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

First published: June 2017

Second edition: December 2017

 

Production reference: 1211217

 

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

 

ISBN 978-1-78839-333-1

www.packtpub.com

Credits

Author

Gaurav Aroraa

Copy Editor

Safis Editing

Reviewer

Jeffrey Chilberto

Project Coordinator

Ulhas Kambali

Commissioning Editor

Merint Mathew

Proofreader

Safis Editing

Acquisition Editor

Denim Pinto

Indexer

Francy Puthiry

ContentDevelopmentEditor

Vikas Tiwari

Graphics

Jason Monteiro

Technical Editor

Jash Bavishi

Production Coordinator

Shantanu Zagade

Foreword

"Our industry does not respect tradition – it only respects innovation."                                                                                           - Satya Nadella

Those words from Satya ring true with microservice architectures. I believe that microservices are a crucial spark of innovation in web development. In an agile world, we need an agile framework in the cloud that is working for us, processing individual actors and services. With this new power, we can deploy a framework that scales, improve resiliency, greatly reduces latency, increases our control of security, and upgrade the system without downtime. Microservices becomes the optimal architecture in our new, cloud-based development environment, and it can result in major cost benefits. 

Gaurav Aroraa masterfully takes us on a journey to explore the history of microservices. He carefully and thoroughly tours the architectural design concepts that accompany the evolution of microservices, from when James Lewis first coined the term to our current tools and implementations. 

The book starts at a high level, with detailed diagrams and descriptions that explain the architectural scenarios, and it uncovers all the values that you’ll receive with a microservices design. At this point, you might ask whether the book is about microservices architecture or is a how-to guide to .NET development. Importantly, the book provides practical knowledge about translating our current applications into this bold new world of microservices. On that journey, it does not speed up. In other books, you move so fast that you can’t understand how or why it works (you can only follow the instructions). You might code and pick up a few tactics along the way, mostly copying and coding by autopilot. However, this book teaches each concept and step in the development process with the attention and focus that it deserves.

In this second edition, Gaurav has crafted the most comprehensive book on microservice development. I’m excited to see him expand on new options for building microservice architectures. Join Gaurav, as you learn about Azure Service Fabric, Service Bus, Message Queuing, and more! 

Personally, I have had the privilege to know Gaurav for a few years now. He’s a Visual Studio and Development MVP (Microsoft Most Valuable Professional) awardee and a leader in the Microsoft cloud development community. I’ve worked closely with him on his powerful contributions to TechNet Wiki. In Building Microservices for .NET Core, I see his dedication and passion shine through. This book needed to be written. I am excited when I find gems like this. Gaurav thoroughly covers every detail, every parameter, and every consideration in tackling this weighty concept of developing a microservices architecture. Read this book, skip ahead where you’re knowledgeable about the given information, and absorb the author’s knowledge; share the book with your business contacts. The development community needs to adopt a microservices approach, and this book is a powerful advocate on that journey.

 

Ed Price

Senior Program Manager

Microsoft Azure CAT (Customer Advisory Team)

Co-Author of Learn to Program with Microsoft Small Basic 

 

About the Author

Gaurav Aroraa has an M.Phil  in computer science. He is a Microsoft MVP, certified as a scrum trainer/coach, XEN for ITIL-F, and APMG for PRINCE-F and PRINCE-P. Gaurav serves as a mentor at IndiaMentor and webmaster at dotnetspider, and he cofounded Innatus Curo Software LLC. In more than 19 years of his career, he has mentored over a thousand students and professionals in the industry. You can reach to Gaurav via Twitter: @g_arora. 

Book writing is not an easy job, as it takes time a lot of time. Sometimes, it needs your personal/family time. So, I want to thank all who motivated me and allowed me to spend time with this book, which I was supposed to spend with them. My first thank you goes to my wife, Shuby Arora, for her constant support throughout. Then, I would like to thank my angel, Aarchi Arora. I would also like to thank the entire Packt team, especially Vikas Tiwari, Jash Bavishi, Diwakar Shukla, Ulhas Kambale, and Denim Pinto for their overnight support. Without the technical reviewer, it's hard to make the content appealing to the readers. So, I would like to thank Jeffrey Chilberto whose precise and to-the-point reviews enriched the book's content. I would also like to thank the entire MVP community, especially Deepak Rajendra – Indian MVP Lead. His words and support further fuelled my desire to write this book. A special thanks to Shivprasad Koirala, who guided me from time to time at various junctures of writing this book. Thanks to the TechNet Wiki community, the Azure community, and to all the lovely folks: Ronen, Kamlesh, Arlan, Syed, Peter Geelen, Pedro aka Pete Laker, and all other champs. Thanks to my friends who motivated me: Chandershekhar Thota, Kanwwar Manish, Ram Nath Rao, Lalit Kale, Pooja (the champ), and Tadit (the bug trapper). Finally, a hearty thanks to Ed Price for his in-depth knowledge and his suggestions to improve the various sections of this book.

About the Reviewer

Jeff Chilberto is a software consultant specializing in the Microsoft technical stack, including Azure, BizTalk, MVC, WCF, and SQL Server. Since his graduation in 1993, Jeff has worked in a wide range of industries, including banking, telecommunications, education, gaming, and healthcare in the United States, Europe, Australia, and New Zealand.  A founding member of the Azure Development Community, Jeff’s focus is on Azure solution architecture and on the development and promotion of the Azure technology and services.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On-demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788393333.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Downloading the color images of this book 

Errata

Piracy

Questions

An Introduction to Microservices

Origin of microservices

Discussing microservices

Monolithic architecture

Service-Oriented architecture

What is a service?

Understanding the microservice architecture

Messaging in microservices

Synchronous messaging

Asynchronous messaging

Message formats

Why should we use microservices?

How does the microservice architecture work?

Advantages of microservices

SOA versus microservices

Prerequisites of the microservice architecture

Understanding the problems with the monolithic architectural style

Challenges in standardizing a .NET stack

Fault tolerance

Scaling

Vertical scaling or scale up

Horizontal scaling or scale out

Deployment challenges

Organizational alignment

Modularity

Big database

Prerequisites for microservices

Functional overview of the application

Solutions for current challenges

Handling deployment problems

Making much better monolithic applications

Introducing dependency injections

Database refactoring

Database sharding and partitioning

DevOps culture

Automation

Testing

Versioning

Deployment

Identifying decomposition candidates within monolithic

Important microservices advantages

Technology independence

Interdependency removal

Alignment with business goals

Cost benefits

Easy scalability

Security

Data management

Integrating monolithic

Overview of Azure Service Fabric

Summary

Implementing Microservices

Introduction

C# 7.0

Entity Framework Core

Visual Studio 2017

Microsoft SQLServer

Size of microservices

What makes a good service?

DDD and its importance for microservices

Domain model design

Importance for microservices

The concept of seam

Module interdependency

Technology

Team structure

Database

Master data

Transaction

Communication between microservices

Benefits of the API gateway for microservices

API gateway versus API management

Revisiting the Flix One case study

Prerequisites

Transitioning to our product service

Migrations

Code migration

Creating our project

Adding the model

Adding a repository

Registering the repositories

Adding a product controller

The ProductService API

Adding EF core support

EF Core DbContext

EF Core migrations

Database migration

Revisiting repositories and the controller

Introducing ViewModel

Revisiting the product controller

Adding Swagger support

Summary

Integration Techniques and Microservices

Communication between services

Styles of collaboration

Integration patterns

The API gateway

The event-driven pattern

Event sourcing

Eventual consistency

Compensating transactions

Competing consumers

Azure Service Bus

Azure queues

Implementing an Azure Service Bus queue

Prerequisites

Sending messages to the queue

Adding configuration settings

Receiving messages from the queue

Summary

Testing Microservices

How to test microservices

Handling challenges

Testing strategies (testing approach)

Testing pyramid

Types of microservice tests

Unit testing

Component (service) testing

Integration testing

Contract testing

Consumer-driven contracts

How to implement a consumer-driven test

How Pact-net-core helps us achieve our goal

Performance testing

End-to-end (UI/functional) testing

Sociable versus isolated unit tests

Stubs and mocks

Tests in action

Getting ready for the test project

Unit tests

Integration tests

Consumer-driven contract tests

Summary

Deploying Microservices

Monolithic application deployment challenges

Understanding the deployment terminology

Prerequisites for successful microservice deployments

Isolation requirements for microservice deployment

Need for a new deployment paradigm

Containers

What are containers?

Suitability of containers over virtual machines

Transformation of the operation team's mindset 

Containers are new binaries

Does it work on your machine? Let's ship your machine!

Introducing Docker

Microservice deployment with Docker overview

Microservice deployment example using Docker

Setting up Docker on your machine

Prerequisites

Creating an ASP.NET Core web application

Summary

Securing Microservices

Security in monolithic applications

Security in microservices

Why won't a traditional .NET auth mechanism work?

JSON Web Tokens

What is OAuth 2.0?

What is OpenID Connect?

Azure Active Directory

Microservice Auth example with OpenID Connect, OAuth 2.0, and Azure AD

Registration of TodoListService and TodoListWebApp with Azure AD tenant

Generation of AppKey for TodoListWebApp

Configuring Visual Studio solution projects

Generate client certificates on IIS Express

Running both the applications

Azure API management as an API gateway

Rate limit and quota policy example

Container security

Other security best practices

Summary

Monitoring Microservices

Instrumentation and telemetry

Instrumentation

Telemetry

The need for monitoring

Health monitoring

Availability monitoring

Performance monitoring

Security monitoring

SLA monitoring

Auditing sensitive data and critical business transactions

End user monitoring

Troubleshooting system failures

Monitoring challenges

Scale

DevOps mindset

Data flow visualization

Testing of monitoring tools

Monitoring strategies

Application/system monitoring

Real user monitoring

Semantic monitoring and synthetic transactions

Profiling

Endpoint monitoring

Logging

Logging challenges

Logging strategies

Centralized logging

Using a correlation ID in logging

Semantic logging

Monitoring in Azure Cloud

Microsoft Azure Diagnostics

Storing diagnostic data using Azure storage

Using Azure portal

Specifying a storage account

Azure storage schema for diagnostic data

Introduction of Application Insights

Other microservice monitoring solutions

A brief overview of the ELK stack

Elasticsearch

Logstash

Kibana

Splunk

Alerting

Reporting

Summary

Scaling Microservices

Scalability overview

Scaling infrastructure

Vertical scaling (scaling up)

Horizontal scaling (scaling out)

Microservice scalability

Scale Cube model of scalability

Scaling of x axis

Scaling of z axis 

Scaling of y axis 

Characteristics of a scalable microservice

Scaling the infrastructure

Scaling virtual machines using scale sets

Auto Scaling

Container scaling using Docker Swarm

Scaling service design

Data persistence model design

Caching mechanism

CacheCow

Azure Redis Cache

Redundancy and fault tolerance

Circuit breakers

Closed state

Open state

Half-Open state

Service discovery

Summary

Introduction to Reactive Microservices

Understanding reactive microservices

Responsiveness

Resilience

Autonomous

Message-driven: a core of reactive microservices

Let's make code reactive

Event communication

Security

Message-level security

Scalability

Communication resilience

Managing data

The microservice ecosystem

Coding reactive microservices

Creating the project

Communication between the application and the database

Client – coding it down

Summary

Creating a Complete Microservice Solution

Architectures before microservices

The monolithic architecture

Challenges in standardizing the .NET stack

Scaling

Service-oriented architecture 

Microservice-styled architecture

Messaging in microservices

Monolith transitioning

Integration techniques

Deployment

Testing microservices

Security

Monitoring

Monitoring challenges

Scale

Component lifespan

Information visualization

Monitoring strategies

Scalability

Infrastructure scaling

Service design

Reactive microservices

Greenfield application

Scoping our services

The book-listing microservice

The book-searching microservice

The shopping-cart microservice

The order microservice

User-authentication

Synchronous versus asynchronous

The book-catalog microservice

The shopping-cart microservice

The order microservice

The user-authentication microservice

Summary

Preface

Distributed systems are always hard to get complete success with. Lately, microservices are getting a considerable amount of attention. With Netflix and Spotify, microservice implementations have the become the biggest success stories in the industry. On the other hand, there are people who are of the opinion that microservices are nothing new or that they are only a rebranding of SOA.

In any case, microservice architecture does have critical advantages—particularly with regard to empowering the agile improvement and conveyance of complex venture applications.

However, there is no clear practical advice on how to implement microservices in the Microsoft ecosystem and, especially, by taking advantage of Azure and the .NET Core framework. This book tries to fill that void.

It explores the concepts, challenges, and strengths around planning, constructing, and operating microservice architectures built with .NET Core 2.0. This book discusses all cross-cutting concerns along with the microservices design. It also highlights some important aspects to consider while building and operating microservices through practical How Tos and best practices for security, monitoring, and scalability.

What this book covers

Chapter 1, An Introduction to Microservices, gets you familiar with microservice architectural styles, history, and how it differs from its predecessors: monolithic architecture and service-oriented architecture (SOA).

Chapter 2, Implementing Microservices, discusses the different factors that can be used to identify and isolate microservices at a high level, what the characteristics of a good service are, and how to achieve the vertical isolation of microservices.

Chapter 3, Integration Techniques and Microservices, gets you familiar with synchronous and asynchronous communication, types of collaborations, and the API gateway.

Chapter 4, Testing Microservices, explains how the testing of microservices is different from the testing of a normal .NET application. It gets you acquainted with the testing pyramid.

Chapter 5, Deploying Microservices, covers how to deploy microservices and best practices. It also takes into account the isolation factor, which is a key success factor, along with setting up continuous integration and continuous delivery to deliver business change at a rapid pace.

Chapter 6, Securing Microservices, explains how to make microservices secure with OAuth and takes you through container security and best practices in general.

Chapter 7, Monitoring Microservices, covers the debugging and monitoring of microservices, which is not a trivial problem but quite a challenging one, as there is no single tool in the .NET ecosystem that is, by design, made for microservices. However, Azure monitoring and troubleshooting is the most promising one.

Chapter 8, Scaling Microservices, explores scalability, which is one of the most critical advantages of pursuing the microservice architectural style. This chapter will explain scalability by design and by infrastructure with respect to the microservice architecture.

Chapter 9, Introduction to Reactive Microservices, gets you familiar with the concept of reactive microservices. You will learn how to build reactive microservices with the use of a reactive extension. It will help you focus on your main task and free you from the chores of communicating across services.

Chapter 10, Creating a Complete Microservice Solution, walks you through all the concepts of microservices that you have learned so far. Then, we will develop an application from scratch while putting all the skills you have learned to use.

What you need for this book

All supporting code samples in this book are tested on .NET Core 2.0 using Visual Studio 2017 update 3 and SQL Server 2008R2 or later on a Windows platform.

Who this book is for

This book is for .NET Core developers who want to learn and understand the microservice architecture and implement it in their .NET Core applications. It’s ideal for developers who are completely new to microservices or just have a theoretical understanding of this architectural approach and want to gain a practical perspective in order to better manage application complexity.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in the text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

"ConnectionStrings": { "ProductConnection": "Data Source=.;Initial Catalog=ProductsDB;Integrated Security=True;MultipleActiveResultSets=True" }

Any command-line input or output is written as follows:

Install-Package System.IdentityModel.Tokens.Jwt

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps:

Log in or register

 

on

 

our website using your email address and password.

Hover the mouse pointer on the

 

SUPPORT

 

tab at the top.

Click on

 

Code Downloads & Errata

.

Enter the name of the book in the

 

Search

 

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

 

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Building-Microservices-with-.NET-Core-2.0-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book 

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/BuildingMicroserviceswith.NETCore2.0_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

An Introduction to Microservices

The focus of this chapter is to get you acquainted with microservices. We will start with a brief introduction. Then, we will define their predecessors: monolithic architecture and Service-Oriented Architecture(SOA). After this, we will see how microservices fare against both SOA and the monolithic architecture. We will then compare the advantages and disadvantages of each one of these architectural styles. This will enable us to identify the right scenario for these styles. We will understand the problems that arise from having a layered monolithic architecture. We will discuss the solutions available to these problems in the monolithic world. At the end, we will be able to break down a monolithic application into a microservice architecture. We will cover the following topics in this chapter:

Origin of microservices

Discussing microservices

Understanding the microservice architecture

Advantages of microservices

SOA versus microservices

Understanding the problems with the monolithic architectural style

Challenges in standardizing a .NET stack

Overview of Azure Service Fabric

Origin of microservices

The term microservices was used for the first time in mid-2011 at a workshop on software architects. In March 2012, James Lewis presented some of his ideas about microservices. By the end of 2013, various groups from the IT industry started having discussions about microservices, and by 2014, they had become popular enough to be considered a serious contender for large enterprises.

There is no official introduction available for microservices. The understanding of the term is purely based on the use cases and discussions held in the past. We will discuss this in detail, but before that, let's check out the definition of microservices as per Wikipedia (https://en.wikipedia.org/wiki/Microservices), which sums it up as:

"Microservices is a specialization of and implementation approach for SOA used to build flexible, independently deployable software systems."

In 2014, James Lewis and Martin Fowler came together and provided a few real-world examples and presented microservices (refer to http://martinfowler.com/microservices/) in their own words and further detailed it as follows:

"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 centralized management of these services, which may be written in different programming languages and use different data storage technologies."

It is very important that you see all the attributes Lewis and Fowler defined here. They defined it as an architectural style that developers could utilize to develop a single application with the business logic spread across a bunch of small services, each having their own persistent storage functionality. Also, note its attributes—it can be independently deployable, can run in its own process, is a lightweight communication mechanism, and can be written in different programming languages.

We want to emphasize this specific definition since it is the crux of the whole concept. And as we move along, it will come together by the time we finish this book.

Discussing microservices

We have gone through a few definitions of microservices; now, let's discuss microservices in detail.

In short, a microservice architecture removes most of the drawbacks of SOAs. It is more code-oriented (we will discuss this in detail in the coming sections) than SOA services.

Slicing your application into a number of services is neither SOA nor microservices. However, combining service design and best practices from the SOA world along with a few emerging practices, such as isolated deployment, semantic versioning, providing lightweight services, and service discovery in polyglot programming, is microservices. We implement microservices to satisfy business features and implement them with reduced time to market and greater flexibility.

Before we move on to understanding the architecture, let's discuss the two important architectures that led to its existence:

The monolithic architecture style

SOA

Most of us would be aware of the scenario where, during the life cycle of an enterprise application development, a suitable architectural style is decided. Then, at various stages, the initial pattern is further improved and adapted with changes that cater to various challenges, such as deployment complexity, large code base, and scalability issues. This is exactly how the monolithic architecture style evolved into SOA, further leading up to microservices.

Monolithic architecture

The monolithic architectural style is a traditional architecture type and has been widely used in the industry. The term monolithic is not new and is borrowed from the UNIX world. In UNIX, most of the commands exist as a standalone program whose functionality is not dependent on any other program. As seen in the following image, we can have different components in the application, such as:

User interface: This handles all of the user interaction while responding with HTML or JSON or any other preferred data interchange format (in the case of web services).

Business logic: All the business rules applied to the input being received in the form of user input, events, and database exist here.

Database access: This houses the complete functionality for accessing the database for the purpose of querying and persisting objects. A widely accepted rule is that it is utilized through business modules and never directly through user-facing components.

Software built using this architecture is self-contained. We can imagine a single .NET assembly that contains various components, as described in the following diagram:

As the software is self-contained here, its components are interconnected and interdependent. Even a simple code change in one of the modules may break a major functionality in other modules. This would result in a scenario where we'd need to test the whole application. With the business depending critically on its enterprise application frameworks, this amount of time could prove to be very critical.

Having all the components tightly coupled poses another challenge—whenever we execute or compile such software, all the components should be available or the build will fail; refer to the preceding diagram that represents a monolithic architecture and is a self-contained or a single .NET assembly project. However, monolithic architectures might also have multiple assemblies. This means that even though a business layer (assembly, data access layer assembly, and so on) is separated, at runtime, all of them will come together and run as one process.

A user interface depends on other components' direct sales and inventory in a manner similar to all other components that depend upon each other. In this scenario, we will not be able to execute this project in the absence of any one of these components. The process of upgrading any one of these components will be more complex as we may have to consider other components that require code changes too. This results in more development time than required for the actual change.

Deploying such an application will become another challenge. During deployment, we will have to make sure that each and every component is deployed properly; otherwise, we may end up facing a lot of issues in our production environments.

If we develop an application using the monolithic architecture style, as discussed previously, we might face the following challenges:

Large code base: This is a scenario where the code lines outnumber the comments by a great margin. As components are interconnected, we will have to bear with a repetitive code base.

Too many business modules: This is in regard to modules within the same system.

Codebase complexity: This results in a higher chance of code-breaking due to the fix required in other modules or services.

Complex code deployment: You may come across minor changes that would require whole system deployment.

One module failure affecting the whole system: This is in regard to modules that depend on each other.

Scalability: This is required for the entire system and not just the modules in it.

Intermodule dependency: This is due to tight coupling.

Spiraling development time: This is due to code complexity and interdependency.

Inability to easily adapt to a new technology: In this case, the entire system would need to be upgraded.

As discussed earlier, if we want to reduce development time, ease of deployment, and improve maintainability of software for enterprise applications, we should avoid the traditional or monolithic architecture.

Service-Oriented architecture

In the previous section, we discussed the monolithic architecture and its limitations. We also discussed why it does not fit into our enterprise application requirements. To overcome these issues, we should take a modular approach where we can separate the components such that they should come out of the self-contained or single .NET assembly.

The main difference between SOA and monolithic is not one or multiple assemblies. As the service in SOA runs as a separate process, SOA scales better compared to monolithic.

Let's discuss the modular architecture, that is, SOA. This is a famous architectural style where enterprise applications are designed as a collection of services. These services may be RESTful or ASMX Web Services. To understand SOA in more detail, let's discuss service first.

What is a service?

Service, in this case, is an essential concept of SOA. It can be a piece of code, program, or software that provides functionality to other system components. This piece of code can interact directly with the database or indirectly through another service. Furthermore, it can be consumed by clients directly, where the client may be a website, desktop app, mobile app, or any other device app. Refer to the following diagram:

Service refers to a type of functionality exposed for consumption by other systems (generally referred to as clients/client applications). As mentioned earlier, it can be represented by a piece of code, program, or software. Such services are exposed over the HTTP transport protocol as a general practice. However, the HTTP protocol is not a limiting factor, and a protocol can be picked as deemed fit for the scenario.

In the following image, Service - direct selling is directly interacting with Database, and three different clients, namely Web, Desktop, and Mobile, are consuming the service. On the other hand, we have clients consuming Service - partner selling, which is interacting with Service - channel partners for database access.

A product selling service is a set of services that interacts with client applications and provides database access directly or through another service, in this case, Service – Channel partners. In the case of Service – direct selling, shown in the preceding image, it is providing functionality to a web store, a desktop application, and a mobile application. This service is further interacting with the database for various tasks, namely fetching and persisting data.

Normally, services interact with other systems via some communication channel, generally the HTTP protocol. These services may or may not be deployed on the same or single servers:

In the preceding image, we have projected an SOA example scenario. There are many fine points to note here, so let's get started. First, our services can be spread across different physical machines. Here, Service - direct selling is hosted on two separate machines. It is possible that instead of the entire business functionality, only a part of it will reside on Server 1 and the remaining on Server 2. Similarly, Service - partner selling appears to be having the same arrangement on Server 3 and Server 4. However, it doesn't stop Service - channel partners being hosted as a complete set on both the servers: Server 5 and Server 6.

A system that uses a service or multiple services in a fashion mentioned in the preceding diagram is called SOA. We will discuss SOA in detail in the following sections.

Let's recall the monolithic architecture. In this case, we did not use it because it restricts code reusability; it is a self-contained assembly, and all the components are interconnected and interdependent. For deployment, in this case, we will have to deploy our complete project after we select the SOA (refer to the preceding diagram and subsequent discussion). Now, because of the use of this architectural style, we have the benefit of code reusability and easy deployment. Let's examine this in the wake of the preceding diagram:

Reusability: Multiple clients can consume the service. The service can also be simultaneously consumed by other services. For example,

OrderService

 is consumed by web and mobile clients. Now,

OrderService

 can also be used by the Reporting Dashboard UI.

Stateless: Services do not persist any state between requests from the client, that is, the service doesn't know, nor care that the subsequent request has come from the client that has/hasn't made the previous request.

Contract-based: Interfaces make it technology-agnostic on both sides of implementation and consumption. It also serves to make it immune to the code updates in the underlying functionality.

Scalability: A system can be scaled up; SOA can be individually clustered with appropriate load balancing.

Upgradation: It is very easy to roll out new functionalities or introduce new versions of the existing functionality. The system doesn't stop you from keeping multiple versions of the same business functionality.

Understanding the microservice architecture

The microservice architecture is a way to develop a single application containing a set of smaller services. These services are independent of each other and run in their own processes. An important advantage of these services is that they can be developed and deployed independently. In other words, we can say that microservices are a way to segregate our services so they can be handled completely independent of each other in the context of design, development, deployment, and upgrades.

In a monolithic application, we have a self-contained assembly of a user interface, direct sales, and inventory. In the microservice architecture, the services part of the application changes to the following depiction: