Modern JavaScript Applications - Narayan Prusty - E-Book

Modern JavaScript Applications E-Book

Narayan Prusty

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

An example-driven guide that explores the world of modern web development with JavaScript

About This Book

  • Explore the new features of ECMAScript 6 and how they can be incorporated to build cutting edge web applications
  • Learn about modern web architectures and build real-world apps on top of them
  • Make use of modern JavaScript tools, techniques and frameworks to enhance your web development skills

Who This Book Is For

This book is for existing JavaScript developers who want to explore some of the modern JavaScript features, techniques, and architectures to develop cutting edge web applications.

What You Will Learn

  • Learn to create single page websites
  • Gain expertise in responsive and dynamic website design
  • Enable Real-time communications between client-client and client-server/server-client
  • Create APIs for large-scale applications
  • Write complete applications using functional reactive programming

In Detail

Over the years, JavaScript has taken significant strides in the world of modern web development to enhance the development of a wide range of applications with different architectures. This book explores the advanced and new features that have arrived in JavaScript and how they can be applied to develop high-quality applications with different architectures.

The book begins by covering a single page application that builds on the innovative MVC approach using AngularJS. As we move forward, the book shows you how to develop an enterprise-level application with the microservices architecture, using Node to build web services. We then focus on network programming concepts and you'll build a real-time web application with websockets.

When you've gained a solid grip on the different architectures, we'll move on to the area where JavaScript shines, that is, UI development. You'll learn to build responsive, declarative UIs with React and Bootstrap. As we near the end of this book, you'll see how the performance of web applications can be enhanced using Functional Reactive Programming (FRP). Along the way, the book also explores how the power of JavaScript can be increased multi-fold.

After reading this book, you will have a solid knowledge of the latest JavaScript techniques, tools, and architecture to build modern web apps.

Style and approach

Covering all the new features in ECMAScript 6, this book takes a project-based approach to introduce you to all the latest techniques, tools, and architectures of JavaScript web development. Each project that the book builds will show you a different angle of the power of JavaScript in modern web development.

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

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 343

Veröffentlichungsjahr: 2016

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.



Table of Contents

Modern JavaScript Applications
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
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
1. Breaking into Microservices Architecture
What is monolithic architecture?
Demerits of monolithic architecture
Scaling monolithic architecture
Writing monolithic server-side applications
Other issues of monolithic architecture
Microservices architecture to the rescue
Merits of microservices architecture
Scaling services
Demerits of microservices architecture
When to use microservices architecture
Data management
Implementing microservices using Seneca
Creating your first Seneca application
Creating actions
Creating plugins
Creating services
Storing data
Integrating Express and Seneca
Summary
2. Building a Coupon Site
Getting started
Architecture of our site
Creating the services
Database service
URL config service
Upload service
Creating the image upload server
Creating the monolithic core
Website walkthrough
Further improvements to the site
Summary
3. Communication between Browsers in Real Time
Terminologies
Stream
Peer-to-peer network model
Real-time data
Introduction to WebRTC
MediaStream API
navigator.getUserMedia
RTCPeerConnection API
Establishing peer-to-peer connection
Transferring MediaStream
RTCDataChannel API
WebRTC applications using PeerJS
PeerServer
PeerJS API
Miscellaneous
Summary
4. Building a Chatroulette
Creating your own PeerServer
Run PeerServer from shell
Using PeerServer library
Creating custom PeerServer
Integrating PeerServer with the Express server
Creating a chatroulette
Building the backend
Building the frontend
Testing the website
Summary
5. Bidirectional Communication in Real Time
Introducing WebSocket
The relationship between WebSocket and HTTP
Sending and receiving data on a WebSocket connection
WebSocket schemes
The interaction of WebSocket with proxy servers, load balancers, and firewalls
The same-origin policy for WebSocket
Introduction to Socket.IO
Setting up your project
Diving into the Socket.IO API
Restricting connections based on origin
Namespaces in Socket.IO
Referring to all connected Socket.IO clients
Rooms in Socket.IO
Joining and leaving a room
Referring to all connected Socket.IO clients in a room
Broadcasting messages and custom events to namespaces and rooms
Broadcasting to a namespace
Broadcasting to a room
Middleware in Socket.IO
Disconnecting manually
Summary
6. Building a Live Score Site
Building the backend
Integrating socket.io server with the Express server
Serving static files and HTML to the users
Serving HTML to the administrator and protecting the admin panel
Socket.IO cookie authentication and broadcasting messages to a namespace
Building the frontend
Testing the website
Summary
7. Functional Reactive Programming
Introduction to reactive programming
Problems with writing reactive code
Functional programming in a nutshell
The advantages of immutable data
Functional data structures
The advantages of pure functions
Functional programming with JavaScript
Functional programming helper functions
Getting started with FRP
EventStreams
Properties
FRP using Bacon.js
Setting up the project
Bacon.js APIs
Creating EventStreams
Creating properties
Merging, filtering, and transforming EventStreams and properties
Merging
Filtering
Transforming
Summary
8. Building an Advanced Profile Search Widget
Errors in Bacon.js
Subscribing to errors
Mapping errors
Retrying a function call
Ending an EventStream or property on error
Handling exceptions
Constant properties
An overview of buses
Subscribing to the end of EventStreams and properties
Unplugging subscribers
Combining and zipping
Lazy evaluation
Type 1
Type 2
Building the profile search widget
Understanding project directories and files
Converting Express.js routes to a functional reactive pattern
Making the user experience better
The company suggestions route
The search result route
Building the frontend
Testing the widget
Summary
9. New Features of Bootstrap 4
Downloading Bootstrap 4
Browser and device support
Understanding the rem and em CSS units
The grid system
Global margin reset
Spacing utility classes
Display headings
Inverse tables
The card component
Card groups, decks, and columns
Outline buttons
Moving from Less to Sass
Text alignment and float utility classes
Reboot
Flexbox support
JavaScript improvements
Adding Tether
The 21:9 aspect ratio class
Customizing Bootstrap 4
Glyphicons dropped
Summary
10. Building User Interfaces Using React
Introducing React
Setting up a basic React project
Virtual DOM
Components
One-way data binding
Isomorphic UI development
Getting started with JSX
Compiling JSX
JSX syntax
Digging into components
Component composition
Component ownership
Reconciliation
Default component property values
Component life cycle methods
componentWillMount()
componentDidMount()
componentWillReceiveProps(nextProps)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate(nextProps, nextState)
componentDidUpdate(prevProps, prevState)
componentWillUnmount()
Mixins
Using Refs
ReactDOMServer.renderToStaticMarkup
Summary
11. Building an RSS Reader Using React and Flux
Understanding Flux
Using Flux.js
Using MicroEvent.js
Introduction to React Router
Creating the RSS feed reader
Setting up the project directories and files
Building the backend
Building the frontend
Defining routes
Creating dispatcher, actions, and stores
Testing the application
Summary
12. New Features of Angular 2
The Angular 2 architecture
Introducing web components
Templates
Custom elements
Shadow DOM
Setting up an Angular 2 project
Angular 2 fundamentals
Styling components and shadow DOM
Angular 2 change detection
Understanding view children and content children
Getting the reference of components of content children and view children
Local template variables
Component lifecycle methods
Writing templates
Rendering a value
Pipes
Handling events
Binding state to element attributes
Two-way data binding
Directives
Attribute directives
Structural directives
Outputs
Two-way data binding with inputs and outputs
Understanding providers
The difference between providers and the viewProviders property
Summary
13. Building a Search Engine Template Using AngularJS 2
Setting up the project
Configuring routes and bootstrapping the app
Generating random search results
Creating route components
Testing the template
Routing life cycle methods
Production mode versus development mode
Summary
14. Securing and Scaling Node.js Applications
Common vulnerabilities in applications
Helmet
Cross-site request forgery
Cross-site scripting
Session fixation
Non-vulnerability based attacks
Denial-of-service attacks
Brute force attacks
Using secure packages
Scaling Node.js servers
Summary
Index

Modern JavaScript Applications

Modern JavaScript Applications

Copyright © 2016 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: July 2016

Production reference: 1140716

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-144-2

www.packtpub.com

Credits

Author

Narayan Prusty

Reviewer

Olivier Pons

Commissioning Editor

Wilson D'souza

Acquisition Editor

Dharmesh Parmar

Content Development Editor

Arshiya Ayaz Umer

Technical Editor

Mohit Hassija

Copy Editor

Madhusudan Uchil

Project Coordinator

Kinjal Bari

Proofreader

Safis Editing

Indexer

Pratik Shirodkar

Graphics

Kirk D'Penha

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade

About the Author

Narayan Prusty is a full-stack developer. He works as a consultant for various startups around the world. He has worked on various technologies and programming languages but is very passionate about JavaScript, WordPress, Ethereum, Solr, React, Cordova, MongoDB, and AWS.

Apart from consulting for various startups, he also runs a blog titled QNimate (http://qnimate.com) and a video-tutorial site titled QScutter (http://qscutter.com), where he shares information about a lot of the technologies he works on. Previously, he wrote a book titled Learning ECMAScript 6, which was published by Packt Publishing.

You can reach Narayan on LinkedIn (https://in.linkedin.com/in/narayanprusty).

About the Reviewer

Olivier Pons is a senior developer who's been building websites for many years. He's a teacher at the University of Sciences (IUT) of Aix-en-Provence, France, ISEN (Institut Supérieur de l'Électronique et du Numérique), G4 Marseille, and École d'Ingénieurs des Mines de Gardanne, where he teaches state-of-the-art web techniques: Node.js, big data/NoSQL, MVC fundamentals, Django/Python, Symfony basics, Wordpress, PHP, HTML, CSS, jQuery/jQuery mobile, AngularJS, Apache, Linux basics, and advanced VIM techniques. He has already done some technical reviews, including the Packt books Learning ExtJS, ExtJS 4 First Look, jQuery hotshots, jQuery Mobile Web Development Essentials, Wordpress 4 Complete, and jQuery 2.0 for Designers Beginner's Guide. In 2011, he left a full-time job as a Delphi developer and PHP expert to concentrate on his own company, HQF Development (http://hqf.fr). He currently runs a number of websites, including http://krystallopolis.fr, http://artsgaleries.com, http://www.battlesoop.fr, http://www.cogofly.com, http://www.papdevis.fr, and http://olivierpons.fr, his own web development blog. He's currently polishing http://cogofly.com and making a keyboard for geek here http://ergofip.com. He works as a consultant, teacher, and project manager and sometimes helps big companies as a senior/highly skilled developer.

www.PacktPub.com

eBooks, discount offers, and more

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://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

 

"JavaScript is the only language that I'm aware of that people feel they don't need to learn before they start using it."

  --Douglas Crockford

The book begins by covering an enterprise-level application with the microservices architecture, using Node.js to build web services. As we move forward, the book shows you how to build a browser-browser application using WebRTC. We then focus on building a real-time web application with WebSockets.

When you've gained a solid grip on the different architectures, you'll see how to write better reactive code using functional reactive programming (FRP). Then, we'll move onto what's new in Bootstrap 4 and how it makes it easier then ever to build responsive sites. As we near the end of this book, you'll see how to build a modern single-page application that builds on the innovative component-based architecture using React and Angular 2.

After reading this book, you will have a solid knowledge of the latest JavaScript techniques, tools, and architecture required to build modern web apps.

What this book covers

Chapter 1, Breaking into Microservices Architecture, teaches what the microservices architecture is and why enterprise-level applications are built using it. We will then explore Seneca.js, which is a microservices toolkit for Node.js.

Chapter 2, Building a Coupon Site, shows you how to build a basic coupon site to demonstrate Seneca.js and the microservices architecture.

Chapter 3, Communication between Browsers in Real Time, teaches you what WebRTC is and how to use it to implement features such as audio/video chat or some other features in websites that need real-time browser-to-browser data transfer or to retrieve audio/video streams from microphones, webcams, or any other device. We will learn to write WebRTC-based applications using PeerJS, which simplifies WebRTC-based application development.

Chapter 4, Building a Chatroulette, shows you how to build a chatroulette to demonstrate WebRTC and PeerJS.

Chapter 5, Bidirectional Communication in Real Time, teaches what WebSockets are and how to achieve bidirectional communication in real-time using WebSockets. We will then explore Socket.IO, which utilizes WebSockets to enable bidirectional communication in real time.

Chapter 6, Building a Live Score Site, shows you how to build a simple live-score site using Socket.IO.

Chapter 7, Functional Reactive Programming, teaches you reactive code and how to write better reactive code using functional reactive programming. We will then explore Bacon.js, which is a functional reactive programming library for JavaScript.

Chapter 8, Building an Advanced Profile Search Widget, helps you build an advanced profile-search widget using Bacon.js.

Chapter 9, New Features of Bootstrap 4, teaches you what's new in Bootstrap 4 and how it makes it easier then ever to create responsive sites.

Chapter 10, Building User Interfaces Using React, teaches you what React.js is and how it makes writing of code for reactive UI easier and takes care of rendering performance and reusability.

Chapter 11, Building an RSS Reader Using React and Flux, shows you how to build a simple RSS reader using React and the Flux architecture.

Chapter 12, New Features of Angular 2, teaches you how to use Angular 2 to build the client side of websites. We will also learn about web components in this chapter.

Chapter 13, Building a Search Engine Template Using AngularJS 2, shows you how to build a search engine template using Angular 2. We will also learn how to build an SPA using Angular 2.

Chapter 14, Securing and Scaling Node.js Applications, teaches you how to make Node.js applications more secure and what the common technologies used for scaling Node.js applications are.

What you need for this book

You can use any operating system that supports Node.js and MongoDB. You will need a browser, but I would recommended you to use the latest version of Chrome as it's way ahead with supporting the new technologies that are covered in this book. You will also need a webcam and microphone. And finally, you will need a working Internet connection.

Who this book is for

This book is for existing JavaScript developers who want to explore some modern JavaScript features, techniques, and architectures in order to develop cutting-edge web applications.

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 e-mail <[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 e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail 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.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

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

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Modern-JavaScript-Applications. 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/ModernJavaScriptApplications_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.

Chapter 1. Breaking into Microservices Architecture

The architecture of server-side application development for complex and large applications (applications with huge number of users and large volume of data) shouldn't just involve faster response and providing web services for wide variety of platforms. It should be easy to scale, upgrade, update, test, and deploy. It should also be highly available, allowing the developers write components of the server-side application in different programming languages and use different databases. Therefore, this leads the developers who build large and complex applications to switch from the common monolithic architecture to microservices architecture that allows us to do all this easily. As microservices architecture is being widely used in enterprises that build large and complex applications, it's really important to learn how to design and create server-side applications using this architecture. In this chapter, we will discuss how to create applications based on microservices architecture with Node.js using the Seneca toolkit.

In this chapter, we'll cover the following topics:

Understanding monolithic architectureScaling, upgrading, deploying, and writing applications based on monolithic architectureDiscussing microservices architecture in depthScaling, upgrading, deploying, and writing applications based on microservices architectureGetting started with SenecaCreating and calling services using Seneca

What is monolithic architecture?

To understand microservices architecture, it's important to first understand monolithic architecture, which is its opposite.

In monolithic architecture, different functional components of the server-side application, such as payment processing, account management, push notifications, and other components, all blend together in a single unit.

For example, applications are usually divided into three parts. The parts are HTML pages or native UI that run on the user's machine, server-side application that runs on the server, and database that also runs on the server. The server-side application is responsible for handling HTTP requests, retrieving and storing data in a database, executing algorithms, and so on. If the server-side application is a single executable (that is, running is a single process) that does all these tasks, then we say that the server-side application is monolithic.

This is a common way of building server-side applications. Almost every major CMS, web servers, server-side frameworks, and so on are built using monolithic architecture.

This architecture may seem successful, but problems are likely to arise when your application is large and complex.

Demerits of monolithic architecture

The following are some of the issues caused by server-side applications built using the monolithic architecture.

Scaling monolithic architecture

As traffic to your server-side application increases, you will need to scale your server-side application to handle the traffic.

In case of monolithic architecture, you can scale the server-side application by running the same executable on multiple servers and place the servers behind a load balancer or you can use round robin DNS to distribute the traffic among the servers:

In the preceding diagram, all the servers will be running the same server-side application.

Although scaling is easy, scaling monolithic server-side application ends up with scaling all the components rather than the components that require greater resource. Thus, causing unbalanced utilization of resources sometimes, depending on the quantity and types of resources the components need.

Let's consider some examples to understand the issues caused while scaling monolithic server-side applications:

Suppose there is a component of server-side application that requires a more powerful or special kind of hardware, we cannot simply scale this particular component as all the components are packed together, therefore everything needs to be scaled together. So, to make sure that the component gets enough resources, you need to run the server-side application on some more servers with powerful or special hardware, leading to consumption of more resources than actually required.Suppose we have a component that requires to be executed on a specific server operating system that is not free of charge, we cannot simply run this particular component in a non-free operating system as all the components are packed together and therefore, just to execute this specific component, we need to install the non-free operating system on all servers, increasing the cost greatly.

These are just some examples. There are many more issues that you are likely to come across while scaling a monolithic server-side application.

So, when we scale monolithic server-side applications, the components that don't need more powerful or special kind of resource starts receiving them, therefore deceasing resources for the component that needs them. We can say that scaling monolithic server-side application involves scaling all components that are forcing to duplicate everything in the new servers.

Writing monolithic server-side applications

Monolithic server-side applications are written in a particular programming language using a particular framework. Enterprises usually have developers who are experts in different programming languages and frameworks to build server-side applications; therefore, if they are asked to build a monolithic server-side application, then it will be difficult for them to work together.

The components of a monolithic server-side application can be reused only in the same framework using, which it's built. So, you cannot reuse them for some other kind of project that's built using different technologies.

Other issues of monolithic architecture

Here are some other issues that developers might face, depending on the technology that is used to build the monolithic server-side application:

It may need to be completely rebuild and redeployed for every small change made to it. This is a time-consuming task and makes your application inaccessible for a long time.It may completely fail if any one of the components fails. It's difficult to build a monolithic application to handle failure of specific components and degrade application features accordingly.It may be difficult to find how much resources are each components consuming.It may be difficult to test and debug individual components separately.

Microservices architecture to the rescue

We saw the problems caused by monolithic architecture. These problems lead developers to switch from monolithic architecture to microservices architecture.

In microservices architecture, the server-side application is divided into services. A service (or microservice) is a small and independent process that constitutes a particular functionality of the complete server-side application. For example, you can have a service for payment processing, another service for account management, and so on; the services need to communicate with each other via a network.

Tip

What do you mean by "small" service?

You must be wondering how small a service needs to be and how to tell whether a service is small or not. Well, it actually depends on many factors such as the type of application, team management, availability of resources, size of application, and how small you think is small. However, a small service doesn't have to be the one that is written is fewer lines of code or provides a very basic functionality. A small service can be the one on which a team of developers can work independently, which can be scaled independently to other services, scaling it doesn't cause unbalanced utilization of recourses, and overall they are highly decoupled (independent and unaware) of other services.

You don't have to run each service in a different server, that is, you can run multiple services in a single computer. The ratio of server to services depends on different factors. A common factor is the amount and type of resources and technologies required. For example, if a service needs a lot of RAM and CPU time, then it would be better to run it individually on a server. If there are some services that don't need much resources, then you can run them all in a single server together.

The following diagram shows an example of the microservices architecture:

Here, you can think of Service 1 as the web server with which a browser communicates and other services providing APIs for various functionalities. The web services communicate with other services to get data.

Merits of microservices architecture

Due to the fact that services are small and independent and communicate via network, microservices architecture solves many problems that monolithic architecture had. Here are some of the benefits of microservices architecture:

As the services communicate via a network, they can be written in different programming languages using different frameworksMaking a change to a service only requires that particular service to be redeployed instead of all the services, which is a faster procedureIt becomes easier to measure how much resources are consumed by each service as each service runs in a different processIt becomes easier to test and debug, as you can analyze each service separatelyServices can be reused by other applications as they interact via network calls

Scaling services

Apart from the preceding benefits, one of the major benefits of microservices architecture is that you can scale individual services that require scaling instead of all the services, therefore preventing duplication of resources and unbalanced utilization of resources.

Suppose we want to scale Service 1 in the preceding diagram. Here is a diagram that shows how it can be scaled:

Here, we are running two instances of Service 1 on two different servers kept behind a load balancer, which distributes the traffic between them. All other services run the same way, as scaling them wasn't required. If you wanted to scale Service 3, then you can run multiple instances of Service 3 on multiple servers and place them behind a load balancer.

Demerits of microservices architecture

Although there are a lot of merits of using microservices architecture compared to monolithic architecture, there are some demerits of microservices architecture as well:

As the server-side application is divided into services, deploying, and optionally, configuring each service separately is a cumbersome and time-consuming task.

Note

Note that developers often use some sort automation technology (such as AWS, Docker, and so on) to make deployment somewhat easier; however, to use it, you still need a good level of experience and expertise with that technology.

Communication between services is likely to lag as it's done via a network.This sort of server-side applications more prone to network security vulnerabilities as services communicate via a network.Writing code for communicating with other services can be harder, that is, you need to make network calls and then parse the data to read it. This also requires more processing. Note that although there are frameworks to build server-side applications using microservices that make fetching and parsing data easier, it still doesn't deduct the processing and network wait time.You will surely need some sort of monitoring tool to monitor services as they may go down due to network, hardware, or software failure. Although you may use the monitoring tool only when your application suddenly stops, to build the monitoring software or use some sort of service, monitoring software needs some level of extra experience and expertise.Microservices-based server-side applications are slower than monolithic-based server-side applications as communication via networks is slower compared to memory.

When to use microservices architecture

It may seem like its difficult to choose between monolithic and microservices architecture, but it's actually not so hard to decide between them.

If you are building a server-side application using monolithic architecture and you feel that you are unlikely to face any monolithic issues that we discussed earlier, then you can stick to monolithic architecture. In future, if you are facing issues that can be solved using microservices architecture, then you should switch to microservices architecture.

If you are switching from a monolithic architecture to microservices architecture, then you don't have to rewrite the complete application, instead you can only convert the components that are causing issues to services by doing some code refactoring. This sort of server-side applications where the main application logic is monolithic but some specific functionality is exposed via services is called microservices architecture with monolithic core. As issues increase further, you can start converting more components of the monolithic core to services.

If you are building a server-side application using monolithic architecture and you feel that you are likely to face any of the monolithic issues that we discussed earlier, then you should immediately switch to microservices architecture or microservices architecture with monolithic core, depending on what suits you the best.

Data management

In microservices architecture, each service can have its own database to store data and can also use a centralized database.

Some developers don't use a centralized database at all, instead all services have their own database to store the data. To synchronize the data between the services, the services omit events when their data is changed and other services subscribe to the event and update the data. The problem with this mechanism is that if a service is down, then it may miss some events. There is also going to be a lot of duplicate data, and finally, it is difficult to code this kind of system.

Therefore, it's a good idea to have a centralized database and also let each service to maintain their own database if they want to store something that they don't want to share with others. Services should not connect to the centralized database directly, instead there should be another service called database service that provides APIs to work with the centralized database. This extra layer has many advantages, such as the underlying schema can be changed without updating and redeploying all the services that are dependent on the schema, we can add a caching layer without making changes to the services, you can change the type of database without making any changes to the services and there are many other benefits. We can also have multiple database services if there are multiple schemas, or if there are different types of database, or due to some other reason that benefits the overall architecture and decouples the services.