Show Menu
Cheatography

Java-Microservices-IMP-Patterns Cheat Sheet by

Contains short description regarding various important design patterns related to Java-Microservices.

Circuit Breaker Design Pattern

Defini­tion:
The Circuit Breaker Design Pattern is used in Java micros­ervices to handle potential failures gracefully and improve the system's resili­ence. It acts as a safety switch to prevent cascading failures in distri­buted systems.
Key Concepts:
Closed State: Requests are allowed through. If failures reach a threshold, the circuit trips to Open.
Open State: Requests are blocked, and failures are immedi­­ately returned. This prevents overlo­­ading the failing service.
Half-Open State: After a timeout, a few requests are allowed to test if the service has recovered. If succes­­sful, the circuit closes again; otherwise, it reopens.
Benefits:
Fault Isolation: Prevents a single service failure from affecting others.
Improved Resili­ence: Allows systems to degrade gracefully instead of failing entirely.
Faster Recovery: Reduces load on failing services, helping them recover faster.
Frameworks like Resili­ence4j or Hystrix are commonly used to implement the Circuit Breaker pattern.

Single Database Per Service

Defini­tion:
The Single Database per Service design pattern is a key principle in micros­ervices archit­ecture that ensures each micros­ervice has its own dedicated database. This pattern supports the autonomy, scalab­ility, and resilience of micros­erv­ices.
Features
Service Ownership: Each micros­ervice is respon­sible for managing its own database schema, data, and access logic.
Decoup­ling: Services are not tightly coupled through shared databases, ensuring changes in one service do not directly affect others.
Data Isolation: Prevents direct access to a service’s data by other services. Commun­ication happens through APIs or events.
Benefits:
Encaps­ula­tion: Data access logic remains confined within the service, promoting loose coupling.
Indepe­ndent Scaling: Each database can be optimized and scaled based on the specific service’s needs.
Technology Flexib­ility: Different micros­ervices can use different types of databases (e.g., SQL, NoSQL) based on their requirements.
Fault Isolation: Database issues in one service don't propagate to others.
Challe­nges:
Data Consis­tency: Mainta­ining consis­tency across multiple services becomes complex, especially during distri­buted transactions.
Data Duplic­ation: Related data may need to be replicated across databases, increasing storage requirements.
Commun­ication Overhead: Cross-­service data access requires inter-­service commun­ication (e.g., via APIs), which can add latency.

API Gateway Design Pattern

Features
Routing: Routes incoming client requests to the approp­riate microservices.
Aggreg­ation:Combines responses from multiple services to provide a single, consol­idated response.
Cross-­Cutting Concerns: Handles common tasks like authen­tic­ation, author­iza­tion, rate limiting, caching, logging, and monitoring.
Protocol Transl­ation: Converts protocols (e.g., HTTP to gRPC) if needed
Advantages
Simplifies client intera­ctions by abstra­cting service details.
Reduces client­-to­-se­rvice commun­ication complexity.
Centra­lizes concerns like security and logging, ensuring consistency.
Challenges
Can become a single point of failure if not designed with redundancy.
May introduce latency due to added processing.
Requires proper scaling to handle high traffic.
Tools Used for Implem­ent­ation:
Netflix Zuul: A flexible API Gateway.
Kong: An open-s­ource API Gateway with plugin support.
Spring Cloud Gateway: A Java-based API Gateway for Spring applications.
AWS API Gateway: A managed solution by AWS.

BulkHead Design Pattern

Key Concept
The system is divided into indepe­ndent partitions (bulkh­eads), like compar­tments in a ship, to contain failures within one partition.
Each bulkhead has dedicated resources (e.g., thread pools, memory, connec­tions) to prevent resource exhaustion from affecting other parts of the system.
Pros:
Fault Isolation: Limits the impact of failures to specific services or components.
Improved Resili­ence: Ensures critical parts of the system remain operat­ional even when some fail.
Resource Protec­tion: Prevents one service from consuming all available resources.
Challenges
Overhead due to managing multiple resource pools.
Requires careful tuning of resource limits for optimal perfor­mance
Implem­ent­ation Tools
Use thread pools, connection pools, or process isolation to allocate resources to specific services.
Frameworks like Resili­ence4j support bulkhead isolation.

Strangler Fig Design Pattern

Key Concept:
Inspired by the way a strangler fig tree grows around a host tree, eventually replacing it.
New features are built as indepe­ndent micros­erv­ices, while the monolithic applic­ation continues to handle legacy functionality.
Over time, the monolith is "­str­ang­led­" as its functi­onality is replaced by microservices.
Process
Identify Modules: Analyze the monolith and identify modules or functi­ona­lities to migrate.
Build New Services: Create micros­ervices for new features or existing modules.
Redirect Traffic: Use an API Gateway or routing layer to direct requests to the approp­riate service (new micros­ervice or monolith).
Decomm­ission Monolith: Gradually phase out the monolith as its respon­sib­ilities are fully transi­tioned to microservices.
Pros
Increm­ental Migration: Avoids the risks of a complete rewrite.
Reduced Downtime: Allows the system to remain operat­ional during migration.
Modern­iza­tion: Enables the adoption of new techno­logies and practices.
Challe­nges:
Complexity in Integr­ation: Requires careful coordi­nation between the monolith and microservices.
Extended Migration Time: The process can take a long time to complete.
The Strangler Fig pattern allows for a smooth and low-risk transition to micros­ervices while contin­uously delivering value.

Fallback Design Pattern

Defini­tion:
The Fallback Design Pattern in micros­ervices is a resilience pattern used to provide a backup response or altern­ative action when a service fails or is unavai­lable. It ensures that the system remains partially functi­onal, offering a better user experience during failures.
Features:
Backup Response: Provides a default or cached response when the primary service fails.
Graceful Degrad­ation: Allows the applic­ation to continue operating with limited functi­onality instead of crashing.
User Impact Mitiga­tion: Minimizes disrup­tions for users by avoiding complete failures.
Pros:
Improves system resilience and user experience.
Reduces the impact of temporary service failures.
Supports fault-­tol­erant design in distri­buted systems.
Challenges
Designing meaningful fallback responses can be complex.
Fallback logic must be carefully tested to avoid unexpected behavior.
Frameworks like Resili­ence4j or Hystrix make implem­enting fallbacks.

Command Query Respon­sib­ility Segreg­ation

Definition
The CQRS (Command Query Respon­sib­ility Segreg­ation) design pattern in micros­ervices separates the operations
that modify data (commands) from the operations that read data (queries).
This pattern optimizes perfor­mance, scalab­ility, and flexib­ility in handling complex business requir­ements.
Key Concepts
Commands: Handle write operations (e.g., creating, updating, or deleting data).
Queries: Handle read operations to retrieve data.
Separate Models: Use distinct data models for write (trans­act­ional consis­tency) and read (optimized for queries).
Pros
Scalab­ility: Scale read and write operations independently.
Perfor­mance: Optimize query responses with denorm­alized or precom­puted data.
Flexib­ility: Tailor read and write models to different requirements.
Challenges
Increased complexity due to managing separate models and synchronization.
Potential for eventual consis­tency between write and read models.
Use frameworks like Axon or Spring Boot to simplify CQRS implem­ent­ation.

Saga Design Pattern

Definition
The Saga Design Pattern is a micros­ervices design pattern for managing distri­buted transactions
in a consistent and reliable way without using a centra­lized transa­ction coordi­nator.
It breaks down a transa­ction into a sequence of smaller,
indepe­ndent steps (local transa­ctions) across services, ensuring eventual consistency.
Concepts
Choreo­graphy: Each service indepe­ndently performs its local transa­ction and publishes events for others to react to.
Orches­tra­tion: A central orches­trator coordi­nates the sequence of steps by invoking the necessary services.
Compen­sation: If a failure occurs, previously completed steps are undone using compen­sating actions.
Pros
Enables distri­buted transa­ctions without locking resources.
Improves system resilience and scalability.
Works well in asynch­ronous and event-­driven architectures.
Implem­ent­ation Tools
Use tools like Kafka or RabbitMQ for event-­driven sagas.
Frameworks like Axon or Camunda help with orches­tra­tion.
The Saga pattern ensures that distri­buted transa­ctions are managed reliably while mainta­ining the indepe­ndence of micros­erv­ices.

Messenging Design Pattern

Definition
The Messaging Design Pattern in micros­ervices facili­tates asynch­ronous commun­ication between services using message brokers or event buses. It decouples services, enabling them to operate indepe­ndently while improving scalab­ility and resili­ence.
Important Concepts
Asynch­ronous Commun­ica­tion: Services exchange messages without waiting for immediate responses.
Message Broker: A central component (e.g., Kafka, RabbitMQ, AWS SQS) routes messages between producers (senders) and consumers (receivers).
Decoup­ling: Producers and consumers are indepe­ndent, knowing only about the message format, not each other.
Pros
Scalab­ility: Services can process messages at their own pace.
Fault Tolerance: Messages can be retried or queued if a service is unavailable.
Decoup­ling: Changes in one service don't require changes in others.
Challenges
Message Ordering: Ensuring the correct sequence of message processing can be complex.
Message Duplic­ation: Requires handling duplicate messages for idempotency.
Operat­ional Overhead: Managing message brokers adds complexity.
Implem­ent­ation Tools
Use messaging protocols like AMQP, MQTT, or Kafka Streams.
Ensure messages are durable, idempo­tent, and well-s­tru­ctured (e.g., JSON, Avro).
The Messaging pattern is fundam­ental in micros­ervices for building resilient, scalable, and loosely coupled systems.
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Spring Framework 4 Cheat Sheet
          Selenium WebDriver Cheat Sheet Cheat Sheet
          ISTQB Test Automation Engineering Cheat Sheet