Book Image

TypeScript Microservices

Book Image

TypeScript Microservices

Overview of this book

In the last few years or so, microservices have achieved the rock star status and right now are one of the most tangible solutions in enterprises to make quick, effective, and scalable applications. The apparent rise of Typescript and long evolution from ES5 to ES6 has seen lots of big companies move to ES6 stack. If you want to learn how to leverage the power of microservices to build robust architecture using reactive programming and Typescript in Node.js, then this book is for you. Typescript Microservices is an end-to-end guide that shows you the implementation of microservices from scratch; right from starting the project to hardening and securing your services. We will begin with a brief introduction to microservices before learning to break your monolith applications into microservices. From here, you will learn reactive programming patterns and how to build APIs for microservices. The next set of topics will take you through the microservice architecture with TypeScript and communication between services. Further, you will learn to test and deploy your TypeScript microservices using the latest tools and implement continuous integration. Finally, you will learn to secure and harden your microservice. By the end of the book, you will be able to build production-ready, scalable, and maintainable microservices using Node.js and Typescript.
Table of Contents (17 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Preface

In the last few years or so, microservices have achieved the rockstar status and are right now one of the most tangible solutions in enterprises to make quick, effective, and scalable applications. Microservices entail an architectural style and pattern in which a huge system is distributed into smaller services that are self-sufficient, autonomous, self-contained, and individually deployable.

The apparent rise of TypeScript and the long evolution from ES5 to ES6 has seen lots of big companies move to ES6 stack. TypeScript, due to its huge advantages like class and module supports, static type checking, and syntax similarity to JavaScript, has become the de facto solution for many enterprises. Node.js, due to its asynchronous, non-blocking, lightweight nature, and for, has been widely appointed by many companies. Node.js written in TypeScript opens doors to various opportunities.

However, microservices have their own difficulties to be dealt with, such as monitoring, scaling, distributing, and service discovery. The major challenge is deploying at scale, as we don't want to end up with system failures. Adopting microservices without actually knowing or addressing these issues would lead to a big issue. The most important part of this book concerns the pragmatic technological independence approach for dealing with microservices so as to leverage the best of everything.

In three parts, this book explains how these services work and the process to build any application the microservices way. You will encounter a design-based approach to architecture and guidance for implementing various microservices elements. You will get a set of recipes and practices for meeting practical, organizational, and cultural challenges to adoption. The goal of this book is to acquaint users with a practical, step-by-step approach for making reactive microservices at scale. This book will take readers into a deep dive with Node.js, TypeScript, Docker, Netflix OSS, and more. Readers of this book will understand how Node.js and TypeScript can be to deploy services that can run independently. Users will understand the evolving trend of serverless computing and the different Node.js capabilities, realizing the use of Docker for containerization. The user will learn how to autoscale the system using Kubernetes and AWS.

I am sure readers will enjoy each and every section of the book. Also, I believe this book adds value for not just Node.js developers but also others who want to play around with microservices and successfully implementing them in their businesses. Throughout this book, I have taken a practical approach by providing a number of examples, including a case study from the e-commerce domain. By the end of the book, you will have learned how to implement microservice architectures using Node.js, the TypeScript framework, and other utilities. These are battle-tested, robust tools for developing any microservice and are written to the latest specifications of Node.js.

Who this book is for

This book is for JavaScript developers seeking to utilize their Node.js and TypeScript skills to build microservices and move away from the monolithic style of architecture. Prior knowledge of TypeScript and Node.js is assumed. This book will help answer some of the important questions concerning what problems a microservice solves and how an organization has to be structured to adopt microservices.

What this book covers

Chapter 1, Debunking Microservices, gives you an introduction to the world of microservices. It begins with the transition from monolithic to microservice architectures. This chapter gets you acquainted with the evolution of the microservices world; answers to frequently asked questions that come up about microservices, and familiarizes you with various microservice design aspects, twelve-factor applications for microservices; and various design patterns for microservice implementations along with their pros, cons, and when to and when not to use them.

Chapter 2, Gearing up for the Journey, introduces necessary concepts in Node.js and TypeScript. It begins with preparing our development environment. It then talks about basic TypeScript essentials such as types, tsconfig.json, writing your custom types for any node module, and the Definitely Typed repository. Then, we move to Node.js, where we write our application in TypeScript. We will learn about some essentials such as Node clusters, Event Loops, multithreading, and async/await. Then, we move to writing our first hello world TypeScript microservice.

Chapter 3, Exploring Reactive Programming, gets into the world of reactive programming. It explores the concepts of reactive programming along with its approaches and advantages. It explains how reactive programming is different from traditional approaches and then moves to practical examples with Highland.js, Bacon.js, and RxJS. It concludes by comparing all the three libraries along with their pros and cons.

Chapter 4, Beginning Your Microservices Journey, begins our microservices case study—the shopping cart microservices. It begins with the functional requirements of the system, followed by overall business capabilities. We start the chapter with architectural aspects, design aspects, and overall components in the ecosystem, before moving to the data layers of microservices, wherein we will have an in-depth discussion on the types of data and how the database layer should be. Then, we develop microservices with the approach of separation of concerns and learn about some microservices best practices.

Chapter 5, Understanding API Gateway, explores the designs involved in an API Gateway. It tells why an API Gateway is required and what its functions are. We will explore various API Gateway designs and the various options available in them. We will look at the circuit breaker and why it plays an important role as part of a client resiliency pattern.

Chapter 6, Service Registry and Discovery, talks about introducing a service registry in your microservices ecosystem. The number of services and/or location of services can remain in flux based on load and traffic. Having a static location disturbs the principles of microservices. This chapter deals with the solution and talks about service discovery and registry patterns in depth. The chapter further explains various options available and discusses Consul and Eureka in detail.

Chapter 7, Service State and Interservice Communication, focuses on interservice communication. Microservices need to collaborate with each other in order to achieve a business capability. The chapter explores various modes of communication. It then talks about next-gen communication styles including RPC and the HTTP 2.0 protocol. We learn about service state and at where the state can be persisted. We go through various kinds of database system along with their use cases. The chapter explores the world of caching, sharing code among dependencies, and versioning strategies, and details how to get client resiliency patterns to handle failures.

Chapter 8, Testing, Debugging, and Documenting, outlines life after development. We learn how to write test cases and plunge into the world of BDD and TDD through some famous toolsets. We see contract testing for microservices—a way to ensure that there are no groundbreaking changes. We then see debugging and how to profile our service and all the options available to us. We move on to documenting and understanding the needs of documentation and all the toolsets involved around Swagger, the tool that we will use.

Chapter 9, Deployment, Logging, and Monitoring, covers deployment and various options involved in it. We see a build pipeline, and we get acquainted with continuous integration and continuous delivery. We understand Docker in detail and dockerize our application by adding Nginx in front of our microservice. We move on to logging and understand the need for a customized, centralized logging solution. We finally move on to monitoring and understanding the various options available, such as keymetrics, Prometheus, and Grafana.

Chapter 10, Hardening Your Application, looks at hardening the application, addressing security and scalability. It talks about security best practices that should be in place to avoids any mishaps. It gives a detailed security checklist that can be used at the time of deployment. We will then learn about scalability with AWS and Kubernetes. We will see how to solve scaling problems with AWS by automatically adding or removing an EC2 instance. The chapter concludes with Kubernetes and its example.

Appendix, What's New in Node.js 10.x and NPM 6.x?, covers about the new update in Node.js v10.x and NPM v6.x. The Appendix is not present in the book, but it is available for the download int the following link: https://www.packtpub.com/sites/default/files/downloads/Whats_New_in_Node.js_10.x_and_NPM_6.x.pdf

My aim for the book was to have this book's topic be relevant, useful, and, most important of all, focused on practical examples useful to career and business-based use cases. I hope you enjoy reading the book as much as I loved writing the book, which surely means that you will have a blast!

To get the most out of this book

This book requires a Unix machine with prerequisites installed. A basic understanding of Node.js and TypeScript is very much needed before proceeding with the book. Most of the code will work in Windows too but with different ways to install it; hence, Linux (Oracle VM Box with Ubuntu is also a perfect fit) is recommended. To get the most out of this book, try to work out the examples and apply the concepts to examples of your own as soon as possible. Most of the programs or case studies in these programs utilize open source software that can be installed or set up with ease. However, a few instances do require setting up a few paid setups.

In Chapter 9, Deployment, Logging, and Monitoring, we need an account on logz.io so as to have a complete ELK setup ready rather than individually managing it. A trial version is available for 30 days, but you can extend some plans. An account for key metrics is needed to uncover its full potential.

In Chapter 10, Hardening Your Application, you need to procure an AWS account for scaling and deployment purposes. You also need to procure Google Cloud Platform for independently testing out Kubernetes rather than going through the manual setup process. The free tier is available for both accounts, but you need to sign up with a credit/debit card.

Download the example code files

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

You can download the code files by following these steps:

  1. Log in or register at www.packtpub.com.
  2. Select the SUPPORT tab.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

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/TypeScript-Microservices. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/TypeScriptMicroservices_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "An example of all the operators in the preceding table can be found at rx_combinations.tsrx_error_handing.ts, and rx_filtering.ts."

A block of code is set as follows:

let asyncReq1=await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log(asyncReq1.data);
let asyncReq2=await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log(asyncReq2.data);

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

sudo dpkg -i <file>.deb
sudo apt-get install -f # Install dependencies

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Open up your instance and then go to the Load Balancing | Load balancers tab."

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.