TypeScript Microservices

Book description

Build robust microservice-based applications that are distributed, fault tolerant, and always available

About This Book
  • Learn to build message-driven services for effective communication
  • Design microservices API using Reactive programming design patterns
  • Deploy, scale and monitor microservices for consistent high performance
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 architecture. Prior knowledge of TypeScript and Node.js is assumed.

What You Will Learn
  • Get acquainted with the fundamentals behind microservices.
  • Explore the behavioral changes needed for moving from monolithic to microservices.
  • Dive into reactive programming, Typescript and Node.js to learn its fundamentals in microservices
  • Understand and design a service gateway and service registry for your microservices.
  • Maintain the state of microservice and handle dependencies.
  • Perfect your microservice with unit testing and Integration testing
  • Develop a microservice, secure it, deploy it, and then scale it
In Detail

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.

Style and approach

This book will be a step by step easy to follow guide with focused examples for building microservices with Typescript.

Table of contents

  1. Title Page
  2. Copyright and Credits
    1. TypeScript Microservices
  3. Packt Upsell
    1. Why subscribe?
    2. PacktPub.com
  4. Contributors
    1. About the author
    2. About the reviewer
    3. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  6. Debunking Microservices
    1. Debunking microservices
      1. Rise of microservices
        1. Wide selection of languages as per demand
        2. Easy handling of ownership
        3. Frequent deployments
        4. Self-sustaining development units
      2. What are microservices?
        1. Principles and characteristics
          1. No monolithic modules
          2. Dumb communication pipes
          3. Decentralization or self-governance
          4. Service contracts and statelessness
          5. Lightweight
          6. Polyglot
        2. Good parts of microservices
          1. Self-dependent teams
          2. Graceful degradation of services
          3. Supports polyglot architecture and DevOps
          4. Event-driven architecture
        3. Bad and challenging parts of microservices
          1. Organization and orchestration
          2. Platform
          3. Testing
          4. Service discovery
      3. Microservice example
    2. Key considerations while adopting microservices
      1. Service degradation
      2. Proper change governance
      3. Health checks, load balancing, and efficient gateway routing
      4. Self-curing
      5. Cache for failover
      6. Retry until
    3. Microservice FAQs
    4. Twelve-factor application of microservices
    5. Microservices in the current world
      1. Netflix
      2. Walmart
      3. Spotify
      4. Zalando
    6. Microservice design aspects
      1. Communication between microservices
        1. Remote Procedure Invocation (RPI)
        2. Messaging and message bus
        3. Protobufs
      2. Service discovery
        1. Service registry for service-service communication
        2. Server-side discovery
        3. Client-side discovery
        4. Registration patterns – self-registration
      3. Data management
        1. Database per service
      4. Sharing concerns
        1. Externalized configuration
        2. Observability
          1. Log aggregation
          2. Distributed tracing
    7. Microservice design patterns
      1. Asynchronous messaging microservice design pattern
      2. Backend for frontends
      3. Gateway aggregation and offloading
      4. Proxy routing and throttling
      5. Ambassador and sidecar pattern
      6. Anti-corruption microservice design pattern
      7. Bulkhead design pattern
      8. Circuit breaker
      9. Strangler pattern
    8. Summary
  7. Gearing up for the Journey
    1. Setting up primary environment
      1. Visual Studio Code (VS Code)
      2. PM2
      3. NGINX
      4. Docker
    2. Primer to TypeScript
      1. Understanding tsconfig.json
        1. compilerOptions
        2. include and exclude
        3. extends
      2. Understanding types
        1. Installing types from DefinitelyTyped
        2. Writing your own types
          1. Using the dts-gen tool
          2. Writing your own *.d.ts file
      3. Debugging
    3. Primer to Node.js
      1. Event Loop
        1. Understanding Event Loop
      2. Node.js clusters and multithreading
      3. Async/await
        1. Retrying failed requests
        2. Multiple requests in parallel
      4. Streams
    4. Writing your first Hello World microservice
    5. Summary
  8. Exploring Reactive Programming
    1. Introduction to reactive programming
      1. Why should I consider adopting reactive programming?
    2. Reactive Manifesto
      1. Responsive systems
      2. Resilient to errors
      3. Elastic scalable
      4. Message-driven
    3. Major building blocks and concerns
      1. Observable streams
      2. Subscription
      3. emit and map
      4. Operator
      5. Backpressure strategy
      6. Currying functions
    4. When to react and when not to react (orchestrate)
      1. Orchestration
        1. Benefits
        2. Disadvantages
      2. Reactive approach
        1. Benefits
        2. Disadvantages
      3. React outside, orchestrate inside
      4. Reactive coordinator to drive the flow
      5. Synopsis
        1. When a pure reactive approach is a perfect fit
        2. When pure orchestration is a perfect fit
        3. When react outside, orchestrate inside is a perfect fit
        4. When introducing a reactive coordinator is the perfect fit
    5. Being reactive in Node.js
      1. Rx.js
      2. Bacon.js
      3. HighLand.js
      4. Key takeaways
    6. Summary
  9. Beginning Your Microservice Journey
    1. Overview of shopping cart microservices 
      1. Business process overview 
      2. Functional view 
      3. Deployment view 
    2. Architecture design of our system 
      1. Different microservices 
      2. Cache microservice
      3. Service registry and discovery
      4. Registrator
      5. Logger 
      6. Gateway
    3. Design aspects involved
      1. Microservice efficiency model 
        1. Core functionalities 
        2. Supporting efficiencies
        3. Infrastructure role
        4. Governance
      2. Implementation plan for shopping cart microservices 
        1. What to do when the scope is not clear
    4. Schema design and database selection 
      1. How to segregate data between microservices
        1. Postulate 1 – data ownership should be regulated via business capabilities 
        2. Postulate 2 – replicate the database for speed and robustness 
      2. How to choose a data store for your microservice
      3. Design of product microservices
    5. Microservice predevelopment aspects
      1. HTTP code 
        1. 1xx – informational 
        2. 2xx – success 
        3. 3xx – redirections 
        4. 4xx – client errors 
        5. 5xx – server errors 
        6. Why HTTP code is vital in microservices?
      2. Auditing via logs 
      3. PM2 process manager
      4. Tracing requests
    6. Developing some microservices for a shopping cart 
      1. Itinerary 
      2. Development setup and prerequisite modules
        1. Repository pattern
        2. Configuring application properties 
        3. Custom health module 
        4. Dependency injection and inversion of control 
          1. Inversify 
          2. Typedi 
        5. TypeORM 
      3. Application directory configurations 
        1. src/data-layer 
        2. src/business-layer
        3. src/service-layer
        4. src/middleware
      4. Configuration files
      5. Processing data
      6. Ready to serve (package.json and Docker) 
        1. package.json 
        2. Docker 
      7. Synopsis
    7. Microservice design best practices
      1. Setting up proper microservice scope 
      2. Self-governing functions 
      3. Polyglot architecture 
      4. Size of independent deployable component 
      5. Distributing and scaling services whenever required
      6. Being Agile 
      7. Single business capability handler
      8. Adapting to shifting needs
      9. Handling dependencies and coupling
      10. Deciding the number of endpoints in a microservice
      11. Communication styles between microservices
      12. Specifying and testing the microservices contract 
      13. Number of microservices in a container 
      14. Data sources and rule engine among microservices 
    8. Summary
  10. Understanding API Gateway
    1. Debunking API Gateway
    2. Concerns API Gateway handles
      1. Security
      2. Dumb gateways
      3. Transformation and orchestration
      4. Monitoring, alerting, and high availability
      5. Caching and error handling
      6. Service registry and discovery
      7. Circuit breakers
      8. Versioning and dependency resolution
    3. API Gateway design patterns and aspects
    4. Circuit breakers and its role
    5. Need for gateway in our shopping cart microservices
      1. Handle performance and scalability
      2. Reactive programming to up the odds
      3. Invoking services
      4. Discovering services
      5. Handling partial service failures
      6. Design considerations
    6. Available API Gateways options
      1. HTTP proxy and Express Gateway
        1. Zuul and Eureka
        2. API Gateway versus reverse proxy NGINX
        3. RabbitMQ
    7. Designing our gateway for shopping cart microservices
      1. What are we going to use?
    8. Summary
  11. Service Registry and Discovery
    1. Introduction to the service registry
    2. What, why, and how of service registry and discovery
      1. The why of service registry and discovery
      2. How service registry and discovery?
        1. Service registration
        2. Service resolution
      3. The what of service registry and discovery
        1. Maintaining service registry
        2. Timely health checks
    3. Service discovery patterns
      1. Client-side discovery pattern
      2. Server-side discovery pattern
    4. Service registry patterns
      1. Self-registration pattern
      2. Third-party registration pattern
    5. Service registry and discovery options
      1. Eureka
        1.  Setting up the Eureka server
        2. Registering with Eureka server
        3. Discovering with Eureka server
        4. Key points for Eureka
      2. Consul
        1. Setting up the Consul server
        2. Talking with Consul server
          1. Registering a service instance
          2. Sending heartbeats and doing a health check
          3. Deregistering an application
          4. Subscribing to updates
        3. Key points for Consul
      3. Registrator
        1. Key points for Registrator
    6. How to choose service registry and discovery
      1. If you select Consul
      2. If you select Eureka
    7. Summary
  12. Service State and Interservice Communication
    1. Core concepts – state, communication, and dependencies 
      1. Microservice state 
      2. Interservice communication
        1. Commands
        2. Queries 
        3. Events 
        4. Exchanging data formats 
          1. Text-based message formats
          2. Binary message formats
      3. Dependencies
    2. Communication styles
      1. NextGen communication styles 
        1. HTTP/2 
        2. gRPC with Apache Thrift 
    3. Versioning microservices and failure handling
      1. Versioning 101 
      2. When a developer's nightmare comes true 
      3. Client resiliency patterns
        1. Bulkhead and retry pattern 
        2. Client-side load balancing or queue-based load leveling pattern 
        3. Circuit breaker pattern 
        4. The fallback and compensating transaction pattern
    4. Case Study – The NetFlix Stack
      1. Part A – Zuul and Polyglot Environment
      2. Part B – Zuul, Load balancing and failure resiliency
    5. Message queues and brokers
    6. Introduction to pub/sub pattern
    7. Sharing dependencies
      1. The problem and solution 
      2. Getting started with bit 
      3. The problem of shared data
    8. Cache
      1. Blessing and curse of caching
      2. Introduction to Redis
        1. Setting up our distributed caching using redis
    9. Summary
  13. Testing, Debugging, and Documenting
    1. Testing
      1. What and how to test
      2. The testing pyramid – what to test?
        1. System tests
        2. Service tests
        3. Contract tests
        4. Unit tests
      3. Hands-on testing
        1. Our libraries and test tool types
          1. Chai
          2. Mocha
          3. Ava
          4. Sinon
          5. Istanbul
        2. Contract tests using Pact.js
          1. What is consumer-driven contract testing?
          2. Introduction to Pact.js
          3. Bonus (containerizing pact broker)
      4. Revisiting testing key points
    2. Debugging
      1. Building a proxy in between to debug our microservices
      2. Profiling process
        1. Dumping heap
        2. CPU profiling
        3. Live Debugging/Remote Debugging
      3. Key points for debugging
    3. Documenting
      1. Need of Documentation
      2. Swagger 101
        1. Swagger Editor and Descriptor
          1. Key points for Swagger  and Descriptor
          2. Swagger Editor
        2. Swagger Codegen
        3. Swagger UI
        4. Swagger Inspector
      3. Possible strategies to use Swagger
        1. Top-down or design-first Approach
        2. Bottom-up approach
      4. Generating a project from a Swagger definition
    4. Summary
  14. Deployment, Logging, and Monitoring
    1. Deployment
      1. Deciding release plan
      2. Deployment options
        1. DevOps 101
          1. Containers
          2. Containers versus Virtual Machine (VMs)
        2. Docker and the world of containers 
          1. Docker components
          2. Docker concepts
          3. Docker command reference
          4. Setting up Docker with NGINX, Node.js, and MongoDB
        3. WebHooks in our build pipeline
        4. Serverless architecture 
    2. Logging 
      1. Logging best practices 
        1. Centralizing and externalizing log storage 
        2. Structured data in logs 
        3. Identifiers via correlational IDs 
        4. Log levels and logging mechanisms 
        5. Searchable logs 
      2. Centralized custom logging solution implementation 
        1. Setting up our environment 
      3. Distributed tracing in Node.js
    3. Monitoring 
      1. Monitoring 101
        1. Monitoring challenges
          1. When to alert and when not to alert?
      2. Monitoring tools 
      3. PM2 and keymetrics 
        1. Keymetrics to monitor application exceptions and runtime problems 
        2. Adding custom metrics
          1. Simple metrics
          2. Counter metric 
          3. Meter
        3. Prometheus and Grafana
    4. Production-ready microservice criteria
    5. Summary
  15. Hardening Your Application
    1. Questions you should be asking while applying security
      1. Core application/core microservice
      2. Middleware
      3. API Gateway
      4. Team and operational activities
    2. Security best practices for individual services/applications
      1. Checking for known security vulnerabilities
        1. Auditjs  
        2. Snyk.io 
      2. Preventing brute force attacks or flooding by adding rate limiters
      3. Protecting against evil regular expressions
      4. Blocking cross-site request forgeries
      5. Tightening session cookies and effective session management
      6. Adding helmet to configure security headers
      7. Avoiding parameter pollution
      8. Securing transmission
      9. Preventing command injection/SQL injection
      10. TSLint/static code analyzers
    3. Security best practices for containers
      1. Securing container builds and standardizing deployments
      2. Securing containers at runtime
    4. Security checklist
      1. Service necessities
      2. Service interactions
      3. Development phase
      4. Deployment
      5. Operations
    5. Scalability
      1. AWS Load Balancer
        1. Benefits of using a load balancer
          1. Fault tolerance
          2. High availability
          3. Flexibility
          4. Security
        2. Health check parameters
          1. Unhealthy threshold
          2. Healthy threshold
          3. Timeout
          4. Health check protocol
          5. Health check port
          6. Interval
        3. Configuring a load balancer
        4. Autoscaling – practical hands on with AWS
          1. Creating the launch configuration
          2. Creating an autoscaling group and configuring it with autoscaling policies
          3. Creating an application load balancer and adding a target group
          4. Time to test
      2. Scaling with Kubernetes
        1. What problem does Kubernetes solve?
        2. Kubernetes concepts
    6. Summary
  16. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

Product information

  • Title: TypeScript Microservices
  • Author(s): Parth Ghiya
  • Release date: May 2018
  • Publisher(s): Packt Publishing
  • ISBN: 9781788830751