Micro-services – DP

INdex

Design patterns

  1. Decentralized Data Management:
    • Implementation:
      1. Each microservice manages its own data and database independently.
      2. Avoids a shared database to prevent tight coupling between services.
    • Java Libraries:
      1. No specific library is tied to this pattern, as it’s more of an architectural principle.
      2. The choice of databases is left to individual microservices. For example, microservices might use Spring Data JPA for database interactions.
  2. Event-Driven Architecture:
    • Implementation:
      1. Microservices communicate asynchronously through events.
      2. Events represent state changes and are used for inter-service communication.
    • Java Libraries:
      1. Apache Kafka: A distributed event streaming platform.
      2. Spring Cloud Stream: Simplifies event-driven microservices development using Spring Boot and Apache Kafka.
      3. Service Discovery:
  • Implementation:
    • Microservices dynamically discover and communicate with each other.
    • Service registry and discovery mechanisms facilitate this dynamic communication.
  • Java Libraries:
    • Netflix Eureka: A service registry for locating services in the cloud.
    • Consul: A tool for service discovery and configuration.

4. API Gateway:

  • Implementation:
    • An entry point that consolidates and manages requests to various microservices.
    • Handles authentication, load balancing, and routing.
  • Java Libraries:
    • Spring Cloud Gateway: A dynamic routing and API gateway powered by Spring WebFlux.
    • Netflix Zuul: A dynamic router and filter for edge services.

5. Circuit Breaker Pattern:

  • Implementation:
    • Protects microservices from failures in dependent services.
    • Opens the circuit if a service is not responsive, preventing cascading failures.
  • Java Libraries:
    • Netflix Hystrix: A library for adding circuit breakers to your services.
    • Resilience4j: A lightweight fault tolerance library.

6. Retry Pattern:

  • Implementation:
    • Retries failed operations to enhance system reliability.
    • Helps in dealing with transient errors.
  • Java Libraries:
    • Spring Retry: A Spring Framework project for retrying failed operations.

7. Saga Pattern:

  • Implementation:
    • Manages long-lived transactions across multiple microservices.
    • Breaks down a transaction into a sequence of smaller, more manageable steps.
    • Handles compensating transactions in case of failures.
  • Java Libraries:
    • No specific library is tied directly to the Saga Pattern, but frameworks like Axon or Eventuate provide support for implementing sagas in Java-based microservices.

High Level Design

Topics to be covered

  1. Back Of Envelope Estimation
  2. Service Discovery
  3. Load balancer
  4. RateLimitting
    • Algorithms
  5. Asynchronous Communication
  6. Cache
  7. Database
    • SQL vs NoSQL
      • CAP theorem
      • Redundancy and replication
  8. Distributed DB
    • Partitions and shading
    • Replication
  9. Reference resources
  10. Interview Optimised

Low Level Design

Index:

  1. Introduction & Representation techniques
    1. OOAD (Object Oriented Analysis and Design) – CDAC reference
      1. Representation using UML(Unified Modelling Language) notation
      2. For Drawing UML Tools-
        • Offline- StarUML,
        • Online – Diagrams.net
      3. OO Analysis and Design Methodolgy
      4. OO Notation
      5. OO tool to draw OOAD Design
  2. OOP (implementation)
    1. OOP Principal
      1. P.I.E.A.
    2. SOLID
    3. Association, Aggregation, Composition
  3. Design pattern (implementation)
    • Behavioural
    • Creational
    • Structural
  4. Interview Outline

What does a OO Designer needs?

  1. OO Concepts
  2. OO Language
  3. OO Analysis and Design Methodolgy
  4. OO Notation
  5. OO tool to draw OOAD Design

OOAD Techniques

  1. Fusion
  2. Jacobson
  3. Rumbaugh
  4. Booch
  5. Rational Unified Process (RUP) with Unified Modeling Language (UML)

OO Design Tools

  1. Rational Software
  2. StarUML

UML Diagrams for OOAD design using RUP

At core we have Models and using which various representation can be drawn for specific analysis-

  1. Use-case Diagrams
  2. Class Diagrams
  3. Object Diagrams
  4. State-chart Diagrams
  5. Sequence Diagrams

Use Case Analysis – Drawing the Use Case Diagram

My take- useful in case of establishing relation between use-case/functionality

  • Stick Figure Represents Actor
  • Oval Represents Use Case
  • The Rectangle represents System Boundary

Use Case Analysis – Use Case Relationships

3 kinds of relationships between use cases

  1. Include
  2. Extend
  3. Uses

Include:

  1. «include» stereotype indicates that one use case “includes” the contents of another use case.
  2. Enables factoring out frequent common behavior

Use case “A” includes use case “B” if :

  1. B describes scenario which is part of scenario of A &
  2. B describes scenario common for a set of use cases including A

Extends:

  1. «extend» stereotype indicates that one use case is “extended” by another use case.
  2. Enables factoring out infrequent behavior or error conditions
  3. Used to show optional behaviour for a use case which will be required only under certain conditions

Uses:

  1. «uses» stereotype indicates that one use case is precondition for executing another use case
  2. Use case “A” uses use case “B” if
    1. B describes a scenario which is not part of scenarios carrying out service A &
    2. B is a precondition for successful invocation of A

Examples


OOAD: Activity Diagram

Depicts business processes and data flows to model the complex logic within the system


OOAD: Sequence Diagrams

Models the time ordering of messages between classifiers to accomplish given
functionality


UML Diagrams: Collaboration Diagrams

Focuses on the structural organisation of objects that send and receive messages.
Known as communication diagrams in UML 2.0.


UML Diagrams: Class Diagrams

Models a collection of static model elements such as classes, their contents and
relationships


UML Diagrams: State machine Diagrams

Describes states of an object and transitions between the states


UML Diagrams: Component Diagrams

Depicts the components, their interfaces and interrelationships


UML Diagrams: Deployment Diagrams

Shows the execution architecture of the application

Micro-services Interview

Objective is to provide a stricture of content – kind of memory map that induces interaction/promption !

Introduction – micro-services breaks the monolith architect into small services that are more manageable and serves a single business process (e.g Notification or billing or payment), it adds to agility to development process and releases – less dependency o other code that we are not modifying.

As compared to monolith

Micro-services provides agility in development as compared to monolith but does introduces more added steps for communication , but because the microservies advantages weighs more than it’s cons conapred to monolith . so microserces is a preferred way of development

Number of Steps involved in making/implementing the microservies working –

  • Creating the micro-services (for details refer corresponding section)
  • Locating the micro-services (for details refer corresponding section)

MServices Design pattern

Micro-services introduction

Index

  • 12 factor app

12 factor app – it was documented by heroku based on their experiences with developing micro-services , it outlines set of best practises and guidelines while building the micro-services app

1. Codebase:

  • Principle: Maintain one codebase in version control, deploy multiple instances.
  • Implementation in Java:
    • Use Git for version control.
    • Organize code into a single repository.
    • Employ branching strategies for various environments (dev, staging, prod).
  • Why It’s Needed in Microservices:
    • Enables consistency across different environments.
    • Facilitates coordinated development and deployment of microservices.

2. Dependencies:

  • Principle: Explicitly declare and isolate dependencies.
  • Implementation in Java:
    • Use Maven or Gradle for dependency management.
    • Declare dependencies in project configuration.
    • Isolate dependencies to prevent conflicts.
  • Why It’s Needed in Microservices:
    • Ensures consistent dependencies across microservices.
    • Facilitates modular and independent development.

3. Config:

  • Principle: Store configuration in the environment.
  • Implementation in Java:
    • Utilize environment variables or configuration files.
    • Leverage Spring Boot configuration options.
    • Externalize sensitive configuration.
  • Why It’s Needed in Microservices:
    • Allows dynamic configuration changes without code modification.
    • Enhances portability across various deployment environments.

4. Backing Services:

  • Principle: Treat backing services as attached resources.
  • Implementation in Java:
    • Use connection pools and externalize configurations.
    • Employ abstractions provided by frameworks (e.g., Spring Data).
    • Avoid hardcoding credentials.
  • Why It’s Needed in Microservices:
    • Promotes independence of microservices from underlying infrastructure.
    • Simplifies integration with different backing services.

5. Build, Release, Run:

  • Principle: Separate build, release, and run processes.
  • Implementation in Java:
    • Use build tools for artifact creation.
    • Adopt continuous integration and deployment practices.
    • Separate build and deployment scripts.
  • Why It’s Needed in Microservices:
    • Enables efficient and controlled release processes.
    • Facilitates automation of deployment pipelines.

6. Processes:

  • Principle: Execute the app as stateless processes.
  • Implementation in Java:
    • Design stateless applications, especially in microservices.
    • Use frameworks like Spring Boot for stateless architectures.
  • Why It’s Needed in Microservices:
    • Enhances scalability and fault tolerance.
    • Allows for easy replication and distribution of microservices.

7. Port Binding:

  • Principle: Export services via port binding.
  • Implementation in Java:
    • Expose services through well-defined ports.
    • Use frameworks like Spring Boot for simplified port binding.
  • Why It’s Needed in Microservices:
    • Enables clear communication channels between microservices.
    • Enhances consistency and predictability in service access.

8. Concurrency:

  • Principle: Scale-out via the process model.
  • Implementation in Java:
    • Design applications for horizontal scalability.
    • Leverage Java’s concurrency utilities.
    • Use technologies like Kubernetes for orchestration.
  • Why It’s Needed in Microservices:
    • Facilitates handling increased loads by adding more instances.
    • Allows dynamic scaling based on demand.

9. Disposability:

  • Principle: Maximize robustness with fast startup and graceful shutdown.
  • Implementation in Java:
    • Optimize application startup time.
    • Use frameworks that support graceful shutdown.
    • Implement exception handling for robustness.
  • Why It’s Needed in Microservices:
    • Enables rapid deployment and updates.
    • Enhances the ability to recover from failures gracefully.

10. Dev/Prod Parity:

  • Principle: Keep development, staging, and production environments as similar as possible.
  • Implementation in Java:
    • Use containerization for environment consistency.
    • Apply infrastructure as code practices.
    • Utilize configuration management tools.
  • Why It’s Needed in Microservices:
    • Reduces the likelihood of bugs due to environment differences.
    • Facilitates smoother transitions between development and production.

11. Logs:

  • Principle: Treat logs as event streams.
  • Implementation in Java:
    • Use logging frameworks like SLF4J.
    • Send logs to centralized log management systems.
    • Structure logs for analysis.
  • Why It’s Needed in Microservices:
    • Aids in monitoring and debugging in a distributed environment.
    • Centralized logs provide a comprehensive view of the system.

12. Admin Processes:

  • Principle: Run admin/management tasks as one-off processes.
  • Implementation in Java:
    • Develop separate scripts or utilities for admin tasks.
    • Use frameworks like Spring Batch for batch processing.
  • Why It’s Needed in Microservices:
    • Allows for efficient and isolated execution of administrative tasks.
    • Prevents interference with regular application processes.

Embracing the 12 Factor App principles in Java-based microservices promotes consistency, scalability, and maintainability. It addresses challenges specific to distributed systems and ensures that microservices are developed and deployed in a cloud-native manner.

Interview Prep

Topics to be covered

  1. Low Level Design
  2. High Level Design
  3. Resources

System Design Resources

Books for HLD

  1. Designing Data-Intensive Application
    • By Martin Klepmann
    • Very Good book for HLD
  2. Insider Guide to SD
    • By Alex xu
    • More specific to Interviews
    • it gives a framework that helps approach a problem
  3. Insider Guide to SD
    • By Maurice Jayson
  4. Solutions Architect
    • Saurabh and Nilanjali Srivastav (pakt publication)
    • more inclined towards architect
    • can refer a few chapters for enhancing knowledge
  5. Fundamentals of Software Architecture
    • Mark Richards (Oreilly publication)
    • more on architecture

Books for LLD (same order can be refereed)

  1. The Object Oriented Thought process
    • By Matt westfield (5TH EDITION)
    • for VERY BEGINNER Who don’t understand class and object and build on Design pattern and SOLID Pattern
  2. Design Pattern: Elements of reusable Object Oriented Software
    • By Gang of four
    • Categorization of patterns
    • How implementation of different pattern can be used
  3. Head First design patterns -Building extensible and maintainable Object oriented software
    • By Eric freeman and Elizabeth
    • with each pattern solve one problem
    • and gives some problem to solve and gives solution to you
  4. Clean Code- A Handbook for Agile Software
    • By Robert martin or uncle bob
    • It talks about maintainable and reusable code
  5. Head First Object-Oriented Analysis and design
    • How in real world the problem is solved is included – extensible and usable to end user.

FAQ
  1. Design BookMyShow kind of App(HashedIn)
    1. based on your input
      • what caching/db to use and why?
  2. Simple in-memory cache,(S)
  3. Design LLD for instagram/Photosharing App
  4. Design a cron jo bscheduler
  5. Design HLD for Twitter system
  6. automated parking lot to minimise the entry and exit times.,(S)
  7. Trafic
    • how will you handle multiple concurrent request not in cache still all going to bacckend
    • search – optimal way to search and partition
    • token generation and submission in optimal way

https://www.geeksforgeeks.org/system-design-url-shortening-service/

System-Design Data-Intensive Application

Aims to bring out the optimal use of available technologies and tools for specific application in data-driven application .

  1. Part-1 : Foundation of Data-Systems
    1. Unit-1 : Reliable , Scalable and Maintainable [ R.S.M. ] code
    2. Unit-2 : Data Models and Query Languages
    3. Unit-3 : Storage and Retrieval
    4. Unit-4 : Encoding and Evolution
  2. Part-2 : Distributed Data
    1. Unit-5 : Replication
    2. Unit-6 : Partitioning
    3. Unit-7 : Transactions
    4. Unit-8 : The trouble with distributed system
    5. Unit-9 : Consistency and Consensus
  3. Part-3 : Derived Data
    1. Batch Processing
    2. Stream Processing
    3. The future of Data Systems

Micro-services

Index-

  1. Overview
  2. Creating micro-services
  3. Locating micro-services
  4. Micro-service Communication
  5. Data Handling

Unit 1: Overview

Background :

Cloud application has several (can discuss separately) advantages . to use those advantages we are moving towards the CLOUD-NATIVE application.
Cloud native applications are composed of smaller, independent, self-contained pieces that are called micro-services.

Opposite of CLOUD-NATIVE application is distributed computing which has some 8 fallacies(0-latency,bandwidth is infinite etc) as mentioned in 1994

Salient features

  • language agnostic
  • should have different phases- deploy and run
  • HTTP/REST communication are synchronous in nature and asynchronisation communication adds to loose coupling between services
  • Language agnostic(free/doubter) comes to forefront ,with standards like AMQP(Advance Messaging Queue Protocol),Message Queuing Telemetry Transport(MQTT) eding out Language specific mechanism like JMS(Java Messaging Service).
  • A saying goes: be liberal in what you accept and be conservative in what you send. that is if you are defining 4 enumeration possibly generated in API request then if in case the 5th one comes up it should log the error and must not fail the application.

Unit 2: Creating micro-service in java

DEFINITION:

Each micro-service should handle a single complete business function.

API-DESIGN

Two strategies: Top-Down and Bottom-Up approach
Mostly used is Top-Down where we first declare the API and then write the corresponding service-code/business code.

SOME NAMING CONVENTION FOR API -DESIGN
  • Use noun and plural instead of verb
PRACTICES FOR MAINTAINING OF CHANGE IN API:
  1. maintain different versions OR,
  2. pass new version in header

Unit 3 : Locating services

Micro-services are designed to be easily scaled . the scaling is done horizontally by scaling individual services.
With multiple-instances of micro-services you need a method to locate the micro-services and load-balancing over different instances of service you are calling.

Following topics involved:

  1. Service registry – consul, zookeeper ,Eureka etc.
  2. Service Invocation -Client-side (sidecar or client Library) or server-side(server proxy)
  3. API gateway
1.Service registry

Service registry is a persistent store that holds all available instances and route on which they can be reached on.

Four reasons why a MICRO-SERVICE must communicate with service-registry:

  1. .Registration – After service deployed. it MUST register with service-registry.
  2. Heart beat – The micro services must send regular heartbeats to show that it is ready to receive requests.
  3. Service discovery In-order to communicate with other services, micro-service must call service-registry to get the list of available instances.
  4. De-registration – when service is down it must be removed from service-registry

Example :
service-registry: consul, Eureka etc.
service-registry are registered by registrar(some service registers have internal to them).
Which Service-Registry to choose:-
Consistency vs Availability:
Most service registries provide partition tolerance and either consistency or availability.A service registry cannot provide all three(tolerance,Consistency, Availability) at same time because of CAP theorem.
(Banking/Finance related service) choose Consistency
Speed(Media Entertainment) choose Availability
For example, Eureka provides availability and both Consul and Apache Zookeeper provide consistency

2.Service Invocation

When a service needs to communicate with another service, it uses the information stored in the service registry. Actual call to micro-service are made either from client-side or from server-side.

Server-Side micro-service calls:

Server-side communication with the micro-service is performed by using a SERVICE PROXY.
SERVICE PROXY is either part of service-registry or a separate service.
micro-services that wants to communicate make a call to WELL KNOWN End points of service proxy .which is responsible for interacting with service registry and forwarding the request.
Load balancing is handled completely on server side.

Disadvantage of Server-Side micro-service calls :
Number of hops is increased.
Advantage:
Testing is easy and proxy can we mocked and tested.

Client-Side micro-service calls:

There is two parts in this process- getting instance(s) of micro-service from service registry and then it makes request to those services.
the micro-service location can be cached on client side to avoid extra path travel in a timeout manner so that if service is down calls don’t fail.
the Request is handled in one of following two ways:
1.Client-library
2.Sidecar

Client Library

It is part of micro-service itself what
it isolates the logic of remote communication. instead of making new we can use 3rd party provided library(Eureka).Other
libraries, such as Netflix Ribbon, provide client-side load balancing.

Sidecar

It is deployed with micro service but runs as a separate process(may be like a config-project corresponding to main project )
A good middle ground between the service proxy and a client library is a sidecar.
Sidecars maintain the service registration with the service registry, and usually also perform

client-side load balancing for outbound calls to other micro-services.
Because sidecars run in their own process, they are independent of language.
Netflix Prana is an open source sidecar that provides the capabilities of the Java based
Ribbon and Eureka client libraries to non-Java applications.

3.API gateway

All requests from external client comes to API-gateway endpoints and then the calls redirected to specific micro service.


UNIT 4: Micro-service communication

Following Topics involved :

  1. Synchronous vs Asynchronous communicate
  2. Fault tolerance (resilience)
Synchronous vs Asynchronous communicate

Synchronous communication is a request that requires a response, whether that be immediately or after some
amount of time. Asynchronous communication is a message where no response is required.

Previous Understanding:
Synchronous communication – one message delivered at a time,and other have to wait until previous once release the resource(thread).

Async support for JAX-RS

Although JAX-RS requests will always be synchronous (you always require a response), you can take advantage of asynchronous programming models. The asynchronous support in JAX-RS 2.0 allows threads to perform other requests while waiting for the HTTP response.

Another option is using reactive libraries like RxJava1. RxJava is a Java implementation of ReactiveX2, a library that is designed to aggregate and filter responses from multiple parallel outbound requests.

Asynchronous messaging (EVENTS)

A request from an external client generally must go through several micro-services before returning a response. If each of these calls is made synchronously, then the total time for the call holds up other requests. The more complex the micro service system and the more interactions between micro-services required per external request, the bigger the resultant latency in your system.
If the requests made in the process can be replaced with asynchronous events, then you should implement the event instead.

The microservices pattern requires each microservice to own its own data. This requirement means when a request comes in, there might be several services that need to update their databases. Services should advertise data changes by using EVENTS that other interested parties can subscribe to.

To coordinate the messaging of your application, you can use any one of the available message brokers and matching client libraries. Some examples that integrate with Java are the AMQP broker6 with the RabibitMQ Java client7, Apache Kafka8, and MQTT9, which is aimed at the Internet of Things space.

In brief:
for better throughput or better response time for ALL THREADS we go by Async Communication.

Internal messaging in Micro-service component

Events can be used within a single microservice.
Using internal events can increase the speed of your response to synchronous requests because you do not have to wait for other synchronous requests to complete before returning a response.
TTake advantage of the Java EE specification support for events. Internal asynchronous events
can be done by using Contexts and Dependency Injection (CDI)1.

Possible Application/Conclusion :
To attain responsiveness from the collective APIs introduce MessageBroker(ACtiveMQ,Kafka) .and increase the no. of threads consumers to more than 1. ,because when all the thread will be added to queue and only 1 thread is picked at a time then rest have to wait. But the incoming Thread don’t have to wait it is put in queue.

It is Kind of partial-utilization of Async feature.(because it says 2 things – the new incoming thread should not have to wait for previous one and already placed should be responding – in this case the new incomming don’t have to wait they are put in queue but collective responsiveness is lacking).

When to use Async and Sync ?

Example : 1.GameOn!
Suppose a user is authenticated to play the game.he sends the request to update room(to accommodate new player) to a service say-mapService. the user is expecting a response whether the request is updated or not.
In this case the Synchronous communication (REST) should be used.
Now the DB has been updated for mapService other micro-services needs to be updated of this change this require no response so it can be done by Event(Asynchronous communication).

In Brief:
Async offer fast processing but synchronous is easy and simple to implement.

Example : 2.On-line retail store.
suppose a user is authenticated and places the Order . the order request to a service needs to respond whether it is successful or not so it’s is synchronous and then the other services which subscriber to this event (like inventory management or the sipping details)will need to update it’s db they don’t require the responding back so these are should be Asynchronous communication.

Fault tolerance

A strong case of micro-service architecture is fault-tolerance and resilience.

Resilient to change:

Consumer OF API:

As a Consumer of API you should Accept unknown attributes
Do not issue an exception if you receive an unexpected variable. If the response contains the information you need, it does not matter what else is provided alongside.
But validate the request against the variables or attributes that you need

Do not validate against variables just because they are provided. If you are not using them
as part of your request, do not rely on them being there.

Producer of API:
  1. Accept unknown attributes as part of the request
  2. Only return attributes that are relevant for the API being invoked
Timeout:

The request must have a timeout. Because we expect services to come and go, we should not be waiting indefinitely for a response.
The asynchronous support in JAX-RS 2.0 has a setTimeout function on the AsynResponse object (see “Synchronous messaging (REST)” on page 34). Tools like Failsafe and Netflix Hystrix have built-in support for timeouts.

CIRCUIT-BREAKERS:

If every-time the timeout issue is occurring then it is not a good way to error out each time, we can give fullback after a limited no. of APIs fail .
The circuit breaker makes a note every time a specific request fails or produces a timeout. If this count reaches a certain level, it prevents further calls from occurring, instead of returning an error instantly
It also incorporates a mechanism for retrying the call, either after a certain amount of time or in reaction to an event.

BulkHeads:

If a compartment of ship fails.it should not sink the whole ship. At each step you should think of removing the dependency.


UNIT 5: HANDLING DATA