Design Microservices v2
Design Microservices v2
Mehmet Ozkaya 1
Architecture Design Journey
Mehmet Ozkaya 2
Architecture Design – Vertical Considerations
Mehmet Ozkaya 3
Way of Learning – The Course Flow
Mehmet Ozkaya 4
Monolithic Architecture
Mehmet Ozkaya 5
Modular Monolithic Architecture Patterns
Architectures Patterns&Principles Non-FR FR
• Monolithic • KISS • Availability • List products
Architecture • Filter products as per
• YAGNI • High number of
• Layered Architecture Concurrent User brand and categories
• Separation of
• Clean Architecture Concerns (SoC) • Maintainability • Put products into the
shopping cart
• Modular Monolithic • SOLID • Flexibility • Apply coupon for discounts
Architecture
• The Dependency • Testable • Checkout the shopping
Rule cart and create an order
• Scalability
• Horizontal Scaling • List my old orders and
• Reliability
order items history
• Load Balancer
• Re-usability
• Monolithic-First
Strategy
Mehmet Ozkaya 6
Design: Modular Monolithic Architecture
Mehmet Ozkaya 7
Microservices Architecture Patterns
Architectures Patterns&Principles Non-FR FR
• Microservices • The Database-per- • High Scalability • List products
Architecture Service Pattern • Filter products as per
• High Availability
• Polygot brand and categories
• Millions of
Persistence
Concurrent User • Put products into the
shopping cart
• Independent • Apply coupon for discounts
Deployable
• Checkout the shopping
• Technology cart and create an order
agnostic
• List my old orders and
• Data isolation order items history
• Resilience and
Fault isolation
Mehmet Ozkaya 8
Design: Microservices Architecture
Mehmet Ozkaya 9
Microservices Communications
Architectures Patterns&Principles Non-FR FR
• Microservices • The Database-per- • High Scalability • List products
Architecture Service Pattern • Filter products as per
• High Availability
• Polygot Persistence brand and categories
• Millions of
• Decompose services by Concurrent User • Put products into the
shopping cart
scalability
• Independent • Apply coupon for discounts
• The Scale Cube Deployable
• Checkout the shopping
• Microservices • Technology agnostic cart and create an order
Decomposition Pattern
• Data isolation • List my old orders and
• Microservices order items history
• Resilience and Fault
Communications
isolation
• HTTP Based RESTful
API design
• GraphQL API design
• gRPC API Design
Mehmet Ozkaya 10
Design: Microservices Architecture with gRPC APIs
Mehmet Ozkaya 11
Microservices Communications Patterns
Architectures Patterns&Principles Microservices Non-FR FR
• Microservices • The Database-per- Communications • High Scalability • List products
Architecture Service Pattern • HTTP Based RESTful API • Filter products as per
• High Availability
• Polygot Persistence brand and categories
• GraphQL API • Millions of Concurrent
• Decompose services by • User • Put products into the
gRPC API shopping cart
scalability
• WebSocket API • Independent
• Apply coupon for
• The Scale Cube Deployable discounts
• Gateway Routing Pattern
• Microservices • Technology agnostic • Checkout the shopping
Decomposition Pattern • Gateway Aggregation cart and create an order
Pattern • Data isolation
• Microservices • List my old orders and
Communications • Gateway Offloading Pattern • Resilience and Fault order items history
isolation
Patterns • API Gateway Pattern
• Backends for Frontends
Pattern-BFF
Mehmet Ozkaya 12
Design:Microservices Architecture with BFF
Mehmet Ozkaya 13
Microservices Async Communications Patterns
Architectures Patterns&Principles Microservices Microservices Async FR
• Microservices • The Database-per- Communications Communications • List products
Architecture Service Pattern • HTTP Based RESTful API • Single-receiver • Filter products as per
• Polygot Persistence Message-based brand and categories
• GraphQL API
Communication (one-to-• Put products into the
• Decompose services by • gRPC API one model) shopping cart
scalability
• WebSocket API •Multiple-receiver • Apply coupon for
• The Scale Cube Message-based discounts
• Gateway Routing Pattern
• Microservices Communication (one-to-
• Checkout the shopping
Decomposition Pattern • Gateway Aggregation Pattern many model-topic) cart and create an orde
• Microservices • Gateway Offloading Pattern• Dependency Inversion • List my old orders and
Communications Principles (DIP) order items history
• API Gateway Pattern
Patterns • Fan-Out
• Backends for Frontends Non-FR
Publish/Subscribe
Pattern-BFF • High Scalability
Messaging Pattern
• Service Aggregator Pattern
• Topic-Queue Chaining & • High Availability
• Service Registry/Discovery Load Balancing Pattern • Millions of Concurrent
Pattern User Ozkaya
Mehmet 14
• Independent
Design: Microservices Architecture with
Fan-Out Publish/Subscribe Messaging Pattern
Mehmet Ozkaya 15
Microservices Data Management Patterns
Architectures Patterns&Principles Microservices Data Microservices Data FR
• Microservices • The Database-per- Choosing Database Commands&Queries • List products
Architecture Service Pattern • The Shared Database Anti- • Materialized View Pattern • Filter products as per
• Polygot Persistence pattern brand and categories
• CQRS Design Pattern
• Decompose services by• Relational and NoSQL • Put products into the
• Event Sourcing Pattern shopping cart
scalability Databases
• Eventual Consistency • Apply coupon for
• The Scale Cube • CAP Theorem–Consistency,
Principle discounts
Availability, Partition
• Microservices Tolerance • Checkout the shopping
Decomposition Pattern cart and create an orde
• Data Partitioning:
• Microservices Horizontal, Vertical and • List my old orders and
Communications Functional Data Partitioning order items history
Patterns
• Database Sharding Pattern Non-FR
• Microservices Data
• High Scalability
Management Patterns
• High Availability
• Millions of Concurrent
User Ozkaya
Mehmet 16
• Independent
Design: Microservices Architecture with CQRS,
Event Sourcing, Eventual Consistency
Mehmet Ozkaya 17
Microservices Distributed Transaction Patterns
Architectures Patterns&Principles Microservices Data Microservices FR
• Microservices • The Database-per- Choosing Database Distributed • List products
Architecture Service Pattern • The Shared Database Anti- Transactions • Filter products as per
• Polygot Persistence pattern, Relational and • SAGA Pattern brand and categories
NoSQL Databases • Put products into the
• Decompose services by • Choreography and
• CAP Theorem–Consistency, shopping cart
scalability Orchestration-based
Availability, Partition SAGA • Apply coupon for
• The Scale Cube Tolerance discounts
• Compensating
• Microservices • Data Partitioning: • Checkout the shopping
Transaction Pattern
Decomposition Pattern Horizontal, Vertical and cart and create an orde
• Microservices Functional Data Partitioning • Dual-Write Problem
• List my old orders and
Communications • Database Sharding Pattern • Transactional Outbox order items history
Patterns Pattern
Microservices Data Non-FR
• Microservices Data Commands&Queries • CDC - Change Data
• High Scalability
Management Patterns Capture
• Materialized View Pattern • High Availability
• Microservices
Distributed • CQRS Design Pattern • Millions of Concurrent
Transaction Pattern • Event Sourcing Pattern User Ozkaya
Mehmet 18
Mehmet Ozkaya 19
Event-Driven Microservices Patterns
Architectures Patterns&Principles Microservices EDA Non-FR FR
• Microservices • The Database-per- • Asynchronous, • High Scalability • List products
Architecture Service Pattern Decoupled • Filter products as per
• High Availability
communication brand and categories
• Event-Driven • Polygot Persistence
• Millions of Concurrent
Microservices • Event Hubs • Put products into the
• Decompose services by User
Architecture shopping cart
scalability • Stream-Processing
• Independent • Apply coupon for
• The Scale Cube • Real-time processing Deployable discounts
• Microservices • High volume events • Technology agnostic • Checkout the shopping
Decomposition Pattern cart and create an order
• Data isolation
• Microservices • List my old orders and
• Resilience and Fault order items history
Communications Patterns
isolation
• Microservices Data
Management Patterns
• Event-Driven
Architecture
Mehmet Ozkaya 20
Event-Driven Microservices Architecture
Mehmet Ozkaya 21
Microservices Deployment Patterns
Architectures Patterns&Principles Microservices Non-FR FR
• Microservices • The Database-per- Deployment • High Scalability • List products
Architecture Service Pattern, Polygot • Docker and Kubernetes • • Filter products as per
High Availability
Persistence, Decompose Architecture, Helm Charts brand and categories
• Event-Driven
services by scalability, • Millions of Concurrent
Microservices
The Scale Cube • Kubernetes Patterns; User • Put products into the
Architecture Sidecar Patterns, Service shopping cart
• Microservices Mesh Pattern • Independent • Apply coupon for
Decomposition Pattern Deployable discounts
• DevOps and CI/CD
• Microservices Pipelines • Technology agnostic • Checkout the shopping
Communications Patterns cart and create an order
• Deployment Strategies; • Data isolation
• Microservices Data Blue-green, Rolling, • List my old orders and
• Resilience and Fault order items history
Management Patterns Canary and A/B isolation
• Event-Driven Architecture Deployment.
• Microservices
Deployments with
Containers and Mehmet Ozkaya 22
Orchestrators
Microservices using Containers and Orchestrators
Mehmet Ozkaya 23
Microservices Resilience Patterns
Architectures Patterns&Principles Microservices Non-FR FR
• Microservices • The Database-per- Resilience • High Scalability • List products
Architecture Service Pattern, Polygot • Resilience Patterns; • Filter products as per
• High Availability
Persistence, Decompose Retry, Circuit-Breaker, brand and categories
• Event-Driven
services by scalability, Bulkhead, Timeout, • Millions of Concurrent
Microservices
The Scale Cube User • Put products into the
Architecture Fallback Pattern shopping cart
• Microservices • Distributed Logging and • Independent • Apply coupon for
Decomposition Pattern Distributed Tracing Deployable discounts
• Microservices • Elastic Stack; • Technology agnostic • Checkout the shopping
Communications Patterns Elasticsearch + Logstash• cart and create an order
Data isolation
• Microservices Data + Kibana • List my old orders and
• Resilience and Fault order items history
Management Patterns • OpenTelemetry using isolation
• Event-Driven Architecture Zipkin
Mehmet Ozkaya 25
Design: Serverless E-Commerce Microservices
Mehmet Ozkaya 26
DEMO: Microservices Architecture Code Review
● https://github1s.com/aspnetrun/run-aspnetcore-microservices
Mehmet Ozkaya 27
Course Target
Mehmet Ozkaya 28
Architecture Design Journey
Mehmet Ozkaya 29
Macroservices to Nanoservices
Mehmet Ozkaya 30
Which architecture approach we should choose ?
Mehmet Ozkaya 31
Architecture Design – Vertical Considerations
Mehmet Ozkaya 32
Way of Learning – The Course Flow
Mehmet Ozkaya 33
Way of Learning – The Course Flow
Mehmet Ozkaya 34
Problem: Increased Traffic, Handle More Request
Problems
● Our E-Commerce Business is growing
Solutions
● Scalabilitiy
● Load Balancer
Mehmet Ozkaya 35
Problem: Break Down Application into Microservices
Problems
● Our E-Commerce Business is growing
Solutions
● Microservices Decomposition Patterns
Mehmet Ozkaya 36
Problem: Direct Client-to-Service Communication
Problems
● Direct Client-to-Service Communication
Solutions
● Well-defined API Design
Mehmet Ozkaya 37
Problem: Inter-service communication makes
heavy load on network traffic
Problems
● Network performance issues on inter-service
communication
● Backend Communication performance requirements
● Streaming requirements
Solutions
● gRPC APIs scalable and fast APIs
framework
Mehmet Ozkaya 38
Problem: Chat with Support Agent
Problems
● Business teams request to answer Customer queries
Solutions
● WebSocket APIs: Build real-time two-way
communication applications
Mehmet Ozkaya 39
Problem: Service-to-Service Communications
Chain Queries
Problems
● HTTP calls to multiple microservices
● Chain Queries
● Increased latency
Solutions
● Aggregate query operations
Mehmet Ozkaya 40
Problem: Long Running Operations Can't Handle with
Sync Communication
Problems
● HTTP calls to multiple microservices
● Chain Queries
Best Practices
● Minimize the communication between the internal
microservices
● make microservices communication in
Solutions
● Asynchronous Message-Based Communications
Solutions
● Scale Stateful Application Horizontal Scaling
Boundaries - Shards/Pods
● Use NoSQL Database to gain partitioning
practices
Question
● How to Choose a Database for Microservices ?
Mehmet Ozkaya 42
Problem: Cross-Service Queries and Write Commands
on Distributed Scaled Databases
Considerations
● Cross-services queries that retrieve data from
several microservices ?
● Separate read and write operations at scale ?
Problems
● Cross-Service Queries with Complex JOIN
operations
● Read and write operations at scale
Solutions
● Microservices Data Query Pattern and Best
Practices
● Materialized View Pattern
Problems
● Distributed Transaction Management
Solutions
● Microservices Distributed Transaction Management
microservices
● Real-time processing
Solutions
● Event-driven architecture for microservices
Mehmet Ozkaya 45
Problem: Database operations are expensive,
low performance
Considerations
● Event-driven architecture comes with latency when
Problems
● Slowliness and Low Performance Communication
performance
Solutions
● Distributed cache
Considerations
● Ensure continuity of service and minimize disruption
Solutions
● Containers and Orchestrators
Mehmet Ozkaya 48
Choosing the Right Architecture for your Application
▪ The Majestik Monolithic
Mehmet Ozkaya 49
Every Architecture has Pros and Cons
Mehmet Ozkaya 50
Design for Business Requirements
Mehmet Ozkaya 51
Way of Learning – The Course Flow
Mehmet Ozkaya 52
How to Follow the Course
▪ I strongly recommended that you should take this course from beginning to end.
▪ If you already familiar some architectures, jump into your target architectures and start to learn from
that section.
▪ All sections are independent from each other and you can easily switch on sections with following
different architectures.
▪ Every section starts with specific problem and solve this problem with learning new patterns-
principles.
▪ If you are only interested in microservices architectures, skip first monolithic, layered, clean and modular
monolithic architectures and jump to microservices architectures.
▪ You can skip some of Microservices vertical topics as per your experience and requirements. If you don't
interest Decomposition, skip "Microservices Decomposition" and continue with "Microservices
Communications" sections.
▪ Jump your problem and learn patterns & principles related that problem to design your final
architecture.
▪ This is reference architecture course that you can take any part of the course according to your
architectural requirements. Mehmet Ozkaya 53
How to Follow the Course - 2
▪ Increase Speed
If you feel comfortable on any particular topic, please increase the video speed
to avoid losing motivation of the course.
▪ Put a Review
Please put a comment and review the course, when you feel ready at any time of
the course, this will help me a lot for further courses.
Mehmet Ozkaya 54
Course Slides
▪ Powerpoint Slides
Find full PowerPoint slides the link in the resource of this video.
Mehmet Ozkaya 55
Understand E-Commerce
Domain
Mehmet Ozkaya 56
Problem: Sell Products Online
Understand Problem
▪ Understand E-Commerce Domain
▪ Functional & non-functional requirements
▪ Use cases
Mehmet Ozkaya 57
Understand E-Commerce Domain
Identify steps;
▪ Requirements and Modelling
▪ Identify User Stories
▪ Identify the Nouns in the user stories
▪ Identify the Verbs in the user stories
Mehmet Ozkaya 58
Understand E-Commerce Domain: Functional Requirements
▪ List products
▪ Filter products as per brand and categories
▪ Put products into the shopping cart
▪ Apply coupon for discounts and see the total cost
all for all of the items in shopping cart
▪ Checkout the shopping cart and create an order
▪ List my old orders and order items history
Mehmet Ozkaya 59
Understand E-Commerce Domain: User Stories (Use Cases)
Mehmet Ozkaya 60
Understand E-Commerce Domain: Non-Functional Requirements
▪ -ilities
Mehmet Ozkaya 61
Request per Second and Acceptable Latency
Mehmet Ozkaya 62
Monolithic Architecture
Mehmet Ozkaya 63
Architecture Design Journey
Mehmet Ozkaya 64
Learn: Monolithic Architecture
▪ Monolithic Architecture
▪ When to use Monolithic Architecture
▪ Benefits of Monolithic Architecture
▪ Challenges of Monolithic Architecture
▪ Monolithic Architecture Pros-Cons
▪ Reference Architectures of Monolithic
Mehmet Ozkaya 65
What is Monolithic Architecture ?
Mehmet Ozkaya 66
When to use Monolithic Architecture
Mehmet Ozkaya 67
When to use Monolithic Architecture
Mehmet Ozkaya 68
Request per Second and Acceptable Latency
Mehmet Ozkaya 69
Benefits of Monolithic Architecture
▪ Simple to Develop
As long as the monolithic approach is a standard way of building
applications, any engineering team has the right knowledge and
capabilities to develop a monolithic application.
▪ Easier debugging and testing
Monolithic applications are much easier to debug and test. Since
a monolithic application has a single code base, we can run end-
to-end testing much faster.
▪ Simple to deploy
When it comes to monolithic applications, you do not have to
handle many deployments, just one file or directory. Easier to
deploy as only a single jar/war file is deployed.
Mehmet Ozkaya 70
Challenges of Monolithic Architecture
Mehmet Ozkaya 71
Learn: Design principles - KISS, YAGNI, DRY
Mehmet Ozkaya 72
Before Design – What we have in our design toolbox ?
Architectures Patterns&Principles Non-FR FR
• Monolithic • DRY • Availability • List products
Architecture • Filter products as per
• KISS • Small number of
Concurrent User brand and categories
• YAGNI
• Put products into the
shopping cart
• Apply coupon for discounts
• Checkout the shopping
cart and create an order
• List my old orders and
order items history
Mehmet Ozkaya 73
Design: First version of Monolithic Architecture
Mehmet Ozkaya 74
Before Design – What we have in our design toolbox ?
Architectures Patterns&Principles Non-FR FR
• Monolithic • DRY • Availability • List products
Architecture • Filter products as per
• KISS • Small number of
Concurrent User brand and categories
• YAGNI
• Put products into the
shopping cart
• Apply coupon for discounts
• Checkout the shopping
cart and create an order
• List my old orders and
order items history
Mehmet Ozkaya 75
Design & Iterate : Monolithic Architecture
Mehmet Ozkaya 76
Evaluate : Monolithic Architecture - E-Commerce App
Benefits
▪ Easy Development
▪ Easy Debug and Test
▪ Easy to Deploy
Drawbacks
▪ Highly tight coupling
▪ Hard to Splitting the code
▪ Violate Separation of concerns
▪ Interlocking Dependencies
without Layers of isolation
Mehmet Ozkaya 77
Problem: Code Become Too Complex Over Time
Problems
● Become Complex over time
Solutions
● Separate UI, Business and Data
● SOLID Design
Mehmet Ozkaya 78
Way of Learning – The Course Flow
Mehmet Ozkaya 79
Layered (N-Layer)
Architecture
Mehmet Ozkaya 80
Problem: Code Become Too Complex Over Time
Problems
● Become Complex over time
Solutions
● Separate UI, Business and Data
● SOLID Design
Mehmet Ozkaya 81
Learn: Layered (N-Layer) Architecture
Mehmet Ozkaya 82
Components of a Layered Architecture
▪ Presentation Layer
Responsible for user interactions with the software
system, for example, a web app.
▪ Application/Business Layer
Handles aspects related to accomplishing functional
requirements including use case implementations.
▪ Database Layer
Responsible for handling data, databases, such as a
SQL database.
Mehmet Ozkaya 83
Design principles - Separation of Concerns (SoC)
Mehmet Ozkaya 84
Design principles - SOLID
▪ Single Responsibility
Each of your components or modules should
responsible only one functionality.
▪ Open-Closed Principle
When we design the system, it should able to extend
without changing existing architecture.
▪ Liskov Substitution Principle
Systems can be substitute each other easily. In our
case we can use plug-in services that we can shift them
easily.
▪ Interface Segregation Principle
States that no code should be forced to depend on
methods it doesn't use.
▪ Dependency Inversion Principle
States that high-level modules should not depend on
low-level modules; both should depend on abstractions.
Mehmet Ozkaya 85
Before Design – What we have in our design toolbox ?
Architectures Patterns&Principles Non-FR FR
• Monolithic • KISS • Availability • List products
Architecture • Filter products as per
• YAGNI • Small number of
• Layered Concurrent User brand and categories
• Seperation of
Architecture
Concerns (SoC) • Maintainability • Put products into the
shopping cart
• SOLID • Apply coupon for discounts
• Checkout the shopping
cart and create an order
• List my old orders and
order items history
Mehmet Ozkaya 86
Design: Layered Monolithic Architecture Steps
Mehmet Ozkaya 87
Design: Layered Monolithic Architecture
Mehmet Ozkaya 88
Way of Learning – The Course Flow
Mehmet Ozkaya 89
Adapt: Layered Monolithic Architecture
Java World
● Apache Web Server
● J2EE
● MySQL
.NET World
● IIS Web Server
● Asp.Net
● SQL Server
Mehmet Ozkaya 90
DEMO: Layered Monolithic Architecture Code Review
● https://github.com/aspnetrun/run-aspnetcore-basics
● https://github1s.com/aspnetrun/run-aspnetcore-basics
Mehmet Ozkaya 91
Way of Learning – The Course Flow
Mehmet Ozkaya 92
Evaluate: Layered Monolithic Architecture
Benefits
● Easy Development, Debug and Deploy
● Separation of Concerns
Drawbacks
● Layers Dependent each other
● Highly Coupling
● Hard to maintanance
● Complexity of codebase
Mehmet Ozkaya 93
Way of Learning – The Course Flow
Mehmet Ozkaya 94
Problem: Highly Coupling Dependent Layers
Problems
● Layers are highly coupled and
Solutions
● Clean Architecture
Mehmet Ozkaya 95
Clean Architecture
Mehmet Ozkaya 96
Problem: Highly Coupling Dependent Layers
Problems
● Layers are highly coupled and
Solutions
● Clean Architecture
Testability
Mehmet Ozkaya 97
Way of Learning – The Course Flow
Mehmet Ozkaya 98
Learn: Clean Architecture
▪ The internal layers contains the business rules and has not
dependency of any third-party library.
Mehmet Ozkaya 99
The Dependency Rule
https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html
https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html
Java World
● Apache Web Server
● J2EE
● MySQL
.NET World
● IIS Web Server
● Asp.Net
● SQL Server
● https://github.com/aspnetrun/run-aspnetcore-realworld
● https://github1s.com/aspnetrun/run-aspnetcore-realworld
Mehmet Ozkaya 106
Way of Learning – The Course Flow
Benefits
● Easy Development, Debug and Deploy
Drawbacks
● Layers are independent but those are technical layers:
Problems
● Our E-Commerce Business is growing
Solutions
● Scalabilitiy
● Load Balancer
Problems
● Our E-Commerce Business is growing
Solutions
● Scalabilitiy
● Load Balancer
▪ -ilities
Load Balancer
● Apache LB
● NGINX
Application Server
● Single JAR / WAR File
● Tomcat Container
Database
● Oracle
● Postgres
● SQL Server
● MySQL
Benefits
● Easy Development, Debug and Deploy
Drawbacks
● Layers are independent but those are technical layers:
▪ Context Switching
When we were working on a feature and needed to work on
any combination of data access, domain or application logic,
we had to switch contexts into different software project.
▪ We had to remember and re-visit codes from other folder
and continue with totally different code base. The folder
structure requires DDD-bounded contexts approaches.
▪ Vertical Slices
When adding a feature in an application, we are developing
into almost all layers in the application code.
▪ Changing the user interface, adding new Use Case classes
into Application Layer, adding fields to models, modifying Data
Access Codes, and so on.
▪ So that means we are highly couple with vertically slice
when developing features.
Problems
● Our E-Commerce Business is growing
Solutions
● Modular Monolithic Architecture
Problems
● Our E-Commerce Business is growing
Solutions
● Modular Monolithic Architecture
Main Benefits
▪ Reduced complexity
▪ Easier to refactor
▪ Better for teams
▪ Single code base harder to implement new changes especially in a large and complex application.
▪ Any code change affects the whole system. Even the smallest change requires full deployment of
the entire application.
▪ Pain point of Monolithic Architectures that is not reliable that a single bug in any module can bring
down the whole monolithic application.
Problems
● Our E-Commerce Business is growing
Solutions
● Modular Monolithic Architecture
Benefits
● Easy Development, Debug and Deploy
Drawbacks
● UI operations are handled in our big monolithic application.
● With adding new features, the Complexity of Presentation UI Operations are going to be nightmare.
● UI layer is generated from server-side, every module is trying to generate their own page.
Problems
● Our E-Commerce Business is growing
● Omnichannel expectations
Solutions
● Separated Presentation with SPA
● Headless Architecture
Load Balancer
● Apache LB
● NGINX
Frontend SPAs
● Angular
● Vue
● React
Backend Application
● Single JAR / WAR File
● Tomcat Container
Database
● Oracle
● Postgres
Mehmet Ozkaya 156
● SQL Server
DEMO: Modular Monolithic Architecture with SPA Code Review
● https://github1s.com/kgrzybek/modular-monolith-with-ddd
Mehmet Ozkaya 157
Way of Learning – The Course Flow
Benefits
● Easy Development, Debug and Deploy
Drawbacks
● Scalability Limits, Database Can't Scale
Problems
● Our E-Commerce Business is growing
● Business teams are separated teams as per departments; Product, Sale, Payment.
● Teams wants to agile and add new features immediately to compete the market
● Handle and process millions of request in a acceptable latency with better performance.
● Required not only technology change but also organizational change is mandatory.
Solutions
● Microservices Architecture
Problems
● Our E-Commerce Business is growing
● Business teams are separated teams as per departments; Product, Sale, Payment.
● Teams wants to agile and add new features immediately to compete the market
● Handle and process millions of request in a acceptable latency with better performance.
● Required not only technology change but also organizational change is mandatory.
Solutions
● Microservices Architecture
▪ Microservices Architecture
▪ When to use Microservices Architecture
▪ Benefits of Microservices Architecture
▪ Challenges of Microservices Architecture
▪ Microservices Architecture Pros-Cons
▪ Reference Architectures of Microservices
▪ Easy Deployment
Microservices enable continuous integration and continuous
delivery, making it easy to try out new ideas and to roll back
if something doesn’t work.
▪ Technology agnostic, Right tool for the job
Small teams can pick the technology that best fits their
microservice and using a mix of technology stacks on their
services.
▪ Resilience and Fault isolation
Microservices are fault toleranced and handle faults correctly
for example by implementing retry and circuit breaking
patterns.
▪ Data isolation
Databases are separated with each other according to
microservices design. Easier to perform schema updates,
because only a single database is affected.
▪ Complexity
Each service is simpler, but the entire system is more
complex. Deployments and Communications can be
complicated for hundreds of microservices.
▪ Network problems and latency
Microservice communicate with inter-service communication,
we should manage network problems. Chain of services
increase latency problems and become chatty API calls.
▪ Development and testing
Hard to develop and testing these E2E processes in
microservices architectures if we compare to monolithic
ones.
▪ Data integrity
Microservice has its own data persistence. Data consistency
can be a challenge. Follow eventual consistency where
possible.
▪ Deployment
Deployments are challenging. Require to invest in quite a lot
of devops automation processes and tools. The complexity
of microservices becomes overwhelming for human
deployment.
▪ Logging & Monitoring
Distributed systems are required to centralized logs to bring
everything together. Centralized view of the system to
monitor sources of problems.
▪ Debugging
Debugging through local IDE isn’t an option anymore. It
won’t work across dozens or hundreds of services.
▪ Make Sure You Have a “Really Good Reason” for Implementing Microservices
Check if your application can do without microservices. When your application requires agility to
time-to-market with zero-down time deployments and updated independently that needs more
flexibility.
▪ Iterate With Small Changes and Keep the Single-Process Monolith as Your “Default”
Sam Newman and Martin Fowler offers Monolithic-First approach. Single-process monolithic
application comes with simple deployment topology. Iterate and refactor with turning a single
module from the monolith into a microservices one by one.
▪ Required to Independently Deploy New Functionality with Zero Downtime
When an organization needs to make a change to functionality and deploy that functionality without
affecting rest of the system.
▪ Required to Independently Scale a Portion of Application
Microservice has its own data persistence. Data consistency can be a challenge. Follow eventual
consistency where possible.
▪ Application Architecture
Monolith has a simple straightforward structure of one
undivided unit. Microservices have a complex structure that
consists of various heterogeneous services and databases.
▪ Scalability
Monolithic application is scaled as a whole single unit, but
microservices can be scaled unevenly. encourages
companies to migrate their applications to microservices.
▪ Deployment
Monolithic application provides fast and easy deployment of
the whole system. Microservices provides zero-downtime
deployment and CI/CD automation.
▪ Development team
If your team doesn’t have experience with microservices and
container systems, building a microservices-based
application will be difficult.
Monolithic Microservices
Problems
● Our E-Commerce Business is growing
● Business teams are separated teams as per departments; Product, Sale, Payment.
● Teams wants to agile and add new features immediately to compete the market
● Handle and process millions of request in a acceptable latency with better performance.
● Required not only technology change but also organizational change is mandatory.
Solutions
● Microservices Architecture
Frontend SPAs
● Angular
● Vue
● React
Backend Microservices
● Java – Spring Boot
● .Net – Asp.net
● JS – NodeJS
Database
● MongoDB – NoSQL Document DB
● Postgres – Relational
Main Considerations
● Decomposition –
Breaking Down
Services
● Communications
● Data Management
● Transaction
Management
● Deployments
● Resilience
Problems
● Our E-Commerce Business is growing
Solutions
● Microservices Decomposition Patterns
Problems
● Our E-Commerce Business is growing
Solutions
● Microservices Decomposition Patterns
Identify steps;
▪ Requirements and Modelling
▪ Identify User Stories
▪ Identify the Nouns in the user stories
▪ Identify the Verbs in the user stories
▪ List products
▪ Filter products as per brand and categories
▪ Put products into the shopping cart
▪ Apply coupon for discounts and see the total cost
all for all of the items in shopping cart
▪ Checkout the shopping cart and create an order
▪ List my old orders and order items history
▪ Customer
▪ Order
▪ Order Details
▪ Product
▪ Shopping Cart
▪ Shopping Cart Items
▪ Supplier
▪ User
▪ Address
▪ Brand
▪ Category
Frontend SPAs
● Angular
● Vue
● React
Backend Microservices
● Java – Spring Boot
● .Net – Asp.net
● JS – NodeJS
Database
● MongoDB – NoSQL Document DB
● Postgres – Relational
Main Considerations
● Decomposition –
Breaking Down
Services
● Communications
● Data Management
● Transaction
Management
● Deployments
● Resilience
Problems
● Direct Client-to-Service Communication
Solutions
● Well-defined API Design
Problems
● Direct Client-to-Service Communication
Solutions
● Well-defined API Design
Steps
● Microservice Communications and Types
▪ one-to-one(queue) implementation
one-to-one(queue) implementation there is a single
producer and single receiver.
▪ Command Patterns offers to receive one queue object and
after that execute the command with incoming message.
This process restarts with receiving new command queue
item.
▪ one-to-many (topic) implementation
In one-to-many (topic) implementation has Multiple
receivers. Each request can be processed by zero to
multiple receivers.
▪ Event-bus or message broker system is publishing events
between multiple microservices and communication provide
with subscribing these events in an async way.
▪ Publish/subscribe mechanism used in Event-driven
microservices architecture.
Mehmet Ozkaya 231
Microservices Communication Styles
Problems
● Direct Client-to-Service Communication
Solutions
● Well-defined API Design
Steps
● Microservice Communications and Types
▪ Well-defined API design is very important in a microservices architecture, communication happens API calls.
▪ Designed APIs should be efficient and not to be chatty communications. APIs must have well-defined
documented and versioning.
▪ Public APIs
Use RESTful APIs over HTTP protocol. RESTful APIs use
JSON payloads for request-response, that easy to check
payloads and easy agreement with clients.
▪ Backend APIs
Inter-service communication can result in a lot of network
traffic. serialization speed and payload size become more
important. Using gRPC is mandatory for increase network
performance.
▪ Focus on the business entities that we expose APIs for our application.
Organize our resources according to business entities and expose via APIs.
▪ Design RESTful APIs for single Product Microservices.
▪ Rule1- REST APIs are designed around "resources"
The best practice is the resource URIs should be based on nouns = the
resource and not verbs. REST API Url: https://e-shop.com/products
▪ https://e-shop.com/products -- Correct
▪ https://e-shop.com/create-product -- Wrong
▪ RESTful API design for E-Commerce Microservices: Customer, Order and Product resources.
▪ How should we design Rest API when you required to get customer orders ?
▪ URL: https://e-shop.com/customers/6/orders
▪ After that we should locate the Order no 22 and get all products:
▪ URL: https://e-shop.com/orders/22/products
▪ Microservices don't share the same code base and don't share data stores. They communicate
through APIs for data operations.
▪ Shopping Cart service requests information about a customer from the Customer service.
▪ Customer service retrieve data with using Repository classes and return Customer entity model
as a JSON object in an HTTP response.
Benefits
● Request can simply sent using browsers.
● HTTP protocol
Drawbacks
● Send multiple request to get relational data
Problems
● Business teams want to see relational data on
● REST: /customer/3/orders/4/products ?
Customer Y ?
● Chatty Calls for enriching data
Solutions
● GraphQL API Design
GraphQL API
▪ Simply send a single query to the GraphQL server that includes the concrete data requirements. The
server then responds with a JSON object.
▪ See example Order and Order Products list as below:
▪ GraphQL is fast
GraphQL is way faster than other communication APIs like REST APIs
because it reduce to multiple calls to get data and provides to query by
choosing only the specific fields.
▪ Single Request
GraphQL get all the data your applications needs in a single request.
Clients get what they request with no over-fetching.
▪ Strongly typed
In GraphQL we describe data before query it. Strongly defined data
types reduce miscommunication.
▪ Hierarchical Structure
GraphQL provides a hierarchical structure where relationships between
objects are defined in a graphical structure.
▪ Evolve API
GraphQL allows an application API to evolve without breaking existing
queries.
Mehmet Ozkaya 260
Disadvantages of GraphQL
▪ REST has become the de-facto standard for designing web APIs,
However, REST APIs are too inflexible to rapidly changing
requirements of the clients.
▪ GraphQL was developed for more flexibility and efficiency that solves
many of the shortcomings and inefficiency calls.
▪ REST has the advantages of being a popular API, and also it is easy
to understand, as well as scalable.
▪ GraphQL is more complex than REST, main drawbacks are error
reporting, caching, and N+1.
▪ GraphQL solves the under-fetching problem that REST can't fetch
hierarchical data at once.
▪ GraphQL and REST are two API styles that have a different approach
when dealing with the transfer of data over HTTP protocols.
https://www.howtographql.com/basics/1-graphql-is-the-better-rest/
Mehmet Ozkaya 265
Fetching Data with GraphQL APIs
https://www.howtographql.com/basics/1-graphql-is-the-better-rest/
Benefits
● Solving the over and under-fetching problem
● Protocol agnostic
Drawbacks
● Increase complexity
● Caching problems
▪ Public APIs
Use RESTful APIs over HTTP protocol. RESTful APIs use
JSON payloads for request-response, that easy to check
payloads and easy agreement with clients.
▪ Backend APIs
Inter-service communication can result in a lot of network
traffic. serialization speed and payload size become more
important. Using gRPC is mandatory for increase network
performance.
communication
● Backend Communication performance requirements
● Streaming requirements
Solutions
● gRPC APIs scalable and fast APIs
framework
Benefits
● High-performance communication
● Multi-language/platform supports
Drawbacks
● Need additional library to generate codes
Problems
● Business teams request to answer Customer queries
Solutions
● WebSocket APIs: Build real-time two-way
communication applications
Benefits
● Full-duplex communication
● Real-time communication
Drawbacks
● A fully HTML5-compliant web browser is
required.
● Not provide intermediary/edge caching.
Question:
▪ How client applications can manage all these different
protocols and communications inside of their applications ?
Problems
● Direct Client-to-Service Communication
Solutions
● Well-defined API Design
Steps
● Microservice Communications and Types
Problems
● Direct Client-to-Service Communication
Solutions
● Well-defined API Design
Steps
● Microservice Communications and Types
▪ Protocol Exchanges
Communication required to use different protocols like exposing HTTP Rest API
but continue to gRPC for internal communications or exposing WebSocket
protocol. Requests must be translate to the other protocols afterwards.
▪ Async Communication Requirements
Client application can't use async communication due to not supported AMQP
protocols. Microservices uses async communication in order to decouple
communication as soon as possible. Hard to implement event-driven publish-
subscribe model.
▪ Payload Changes for Different Clients
Web, Mobile and other client applications might be required different payloads
when communicating with internal services. It requires to optimize data
responses from services tailored with client applications.
Benefits
● Reverse proxy, Routing, Aggregation
Drawbacks
● Single API Gateway = single-point-of-failure
risk
● Business complexity in API Gateway
Problems
● Frontend client applications has different UI and
data.
● Client codes complex and hard to maintain for
Solutions
● Client focused Interfaces
Benefits
● Client focused Interfaces
client applications
Drawbacks
● Increased Latency
● Chain Queries
● Increased latency
Solutions
● Aggregate query operations
microservices
● Centralizing logic into a specialized microservice
Registry/Discovery
● Provide to register and discover microservices in
the cluster
● Keep track of microservice locations beforehand
Drawbacks
● Increased Latency
● Vue
● React
API Gateways
● Kong Gateway
● Express Gateway
Service Registry
● Netflix Eureka
● Chain Queries
Best Practices
● Minimize the communication between the internal
microservices
● Make microservices communication in
Solutions
● Asynchronous Message-Based Communications
● Chain Queries
Best Practices
● Minimize the communication between the internal
microservices
● Make microservices communication in
Solutions
● Asynchronous Message-Based Communications
▪ Microservice publishes an event when something happens. Price change in a product microservice:
Price Changed event can subscribed from SC microservice in order to update basket price.
▪ Provide to broke dependency of classes by inverting dependencies, inject dependent classes via
constructor.
▪ Upper-level modules or classes and lower-level classes must not be dependent on modules.
▪ Lower-level modules must be dependent on higher-level modules (interfaces of modules).
▪ Use a queue that acts as a buffer between the service to avoid loss data if the service to fail.
▪ Services can be down or getting exception or taken offline for maintenance, then events will be loses,
disappeared and can't process after the subscriber service is up and running.
▪ Put Amazon SQS between EventBridge and Ordering microservices.
▪ Store this event messages into SQS queue with durable and persistent manner, no message will get lost.
Queue can act as a buffering load balancer.
● Vue
● React
API Gateways
● Kong Gateway
● Express Gateway
Message Brokers
● Kafka
● Event-driven Microservices
Drawbacks
● Single Point of Failure - Message Broker
● Hard to Debugging
Considerations
● State-less or state-ful services
Problems
● Database are stateful service
horizontally
Solutions
● Scale Stateful Application Horizontal Scaling
Boundaries - Shards/Pods
● Use NoSQL Database to gain easy partitioning
features
▪ Reliability
Kafka is distributed, partitioned, replicated and fault
tolerance. So it is also High Availability.
▪ Scalability
Since its distributed architecture, Kafka scales easily without
any down time.
▪ Durability
Kafka uses Distributed commit log. This persists to events
on disk as log commit very fast. Its durable for infinitive or a
given parameter days or weeks.
▪ Performance
Kafka has high throughput for both publishing and
subscribing messages. It is distributed event streaming
platform capable of handling trillions of events a day.
▪ Kafka has better throughput, built-in partitioning, replication,
and fault-tolerance architecture.
Mehmet Ozkaya 368
Apache Kafka Use Cases
▪ Messaging
Message brokers are used to decouple services from each
other. In event-driven architecture, Kafka is used as an event
router, and microservices publish and subscribe to the events.
▪ Metrics
Kafka is often used for operational monitoring data.
Aggregating statistics from distributed applications to produce
centralized feeds of operational data.
▪ Log Aggregation
Log aggregation solution that collect logs from multiple
services. Log aggregation collects physical log files servers
and puts them in a central place for processing.
▪ Stream Processing
Kafka process data in processing pipelines consisting of
multiple stages. Storm and Spark Streaming read data from a
topic and processes it.
▪ Queue Name
The name of the queue we have defined.
▪ Durable
Determines the lifetime of the queue. If we want persistence, we have to set it true.
▪ Exclusive
Contains information whether the queue will be used with other connections.
▪ AutoDelete
Contains information about deletion of the queue with the data sent to the queue passes to the consumer side.
https://www.rabbitmq.com/tutorials/amqp-concepts.html
Mehmet Ozkaya 377
RabbitMQ Exchange Types
▪ Fanout Exchange
Used in situations where the message should be sent
to more than one queue. Especially applied in
Broadcasting systems.
▪ Mainly used for games for global announcements.
▪ Headers Exchange
Guided by the features added to the header of the
message. Routing-Key used in other models is not
used.
▪ Transmits to the correct queue with a few features and
descriptions in message headers.
▪ The attributes on the header and the attributes on the
queue must match each other’s values.
https://www.rabbitmq.com/tutorials/amqp-concepts.html
Mehmet Ozkaya 379
RabbitMQ Architecture
▪ How can we manage this stateful data when scaling the application ?
▪ CAP Theorem to manage stateful server horizontal scaling operation.
▪ Microservices are "stateless" services that can scale easily.
▪ Databases have "state" and need to consider CAP Theorem when horizontally scaling for stateful servers.
Problems
● Database are stateful service
horizontally
Solutions
● Scale Stateful Application Horizontal Scaling
Boundaries - Shards/Pods
● Use NoSQL Database to gain easy partitioning
features
Question
● How to Choose a Database for Microservices ?
▪ Every microservice has its own data, the data integrity and
data consistency should consider very carefully.
▪ Microservices should not share database with each other.
▪ Microservices share data over the application microservices
with using Rest APIs. Broke the unnecessary dependencies
between microservices.
▪ If there is an update on 1 microservices database schema,
the update shouldn’t be directly affect to other microservices.
▪ Limit the scope of changes on microservices when any
database schema changes happened.
▪ We can pick different databases as per microservices which
database can pick the best option: "polyglot persistence"
principle.
▪ Challenges: Duplicated or partitioned data can make problems
of data integrity and data consistency. Strict or Eventual
consistency. Mehmet Ozkaya 394
Polyglot Persistence Principle in Microservices-2
▪ Separating databases can gives us to ability to pick the best optimized database for our
microservices.
▪ Can choices include relational, document, key-value, and even graph-based data stores.
▪ Using the most efficient database depending on the service requirements and functionality.
Benefits
▪ Transaction management, that we don't need to span the
transactions over the microservices.
▪ Decrease duplicate data. Since data is fully constrained, we
can easily execute complicated queries with joins.
▪ Able to follow ACID. Consistency of data and state easily
manage when process fails.
Drawbacks
▪ Microservices with shared databases can’t easily scale.
▪ Shared database will become a single point of failure.
▪ Microservices won’t be independent in terms of
development and deployment.
▪ Use Right Tool for Right Job, Use the best data store for your data.
▪ Don't use Relational Database Everywhere
If using Relational Database for all microservices, would probably
going wrong way, consider other data stores to data requirements.
▪ Don't use Single Data Store Technology, Differentiate
Choose Alternatives to relational databases; Key/value stores,
Document, Search engine, Time series, Column family, Graph
databases.
▪ Focus The Data Type That Need to Store
Consider the type of data that you have.
▪ Store JSON documents in No-SQL Document database.
▪ Put transactional data into a Relational SQL database.
▪ Use a time series data base for telemetry databases.
▪ Choose Blob Data Storage for blob datas.
▪ Put application logs into Elastic Search Databases.
Solutions
● Scale Stateful Application Horizontal Scaling
Boundaries - Shards/Pods
● Use NoSQL Database to gain partitioning
practices
Question
● How to Choose a Database for Microservices ?
Mehmet Ozkaya 419
How to Choose a Database for Microservices ?
(Question Set)
▪ Data Consistency Level
Do we need Strict-Strong consistency or Eventual consistency ?
▪ Do we need ACID compliance ? Should follow Eventual consistency
in microservices to gain high scalability and availability.
▪ Fixed or Flexible Schema Choise, Predictable or Dynamic Data
Are we work with fixed or flexible schema that need to change
frequently, dynamically changed data ?
▪ Are we have Predictable Data or Dynamic Data ?
▪ High or Low Data Volume, Predictable or Un-predictable Data
Are we work with High Volume Data or Low Volume Data ?
▪ Can we have predictable data that we store our microservices
database ?
▪ NoSQL Databases prioritize partition tolerance that handling large
amount of data or data coming in high velocity.
database
● Running out of disk space
Solutions
● Data Partitioning
● Improve availability
● Increase scalability
● Increase performance
● Improve security
● Improve data management, Operation
▪ Increase Scalability
When divide data across multiple data partitions into
separate db servers, we can scale out the system
without worrying any hardware limits.
▪ Improve Availability
With Separating data across multiple servers, we
protect our systems for a single point of failures.
▪ Increase Performance (Query and operations)
Instead of querying whole database, system query only
smaller components.
▪ Improve Security
By storing sensitive and non-sensitive data into different
partitions.
▪ Improve Data Management
Due to divide tables and indexes with different
partitions, its more easy to manage small units and
easy to maintenance. Mehmet Ozkaya 430
Horizontal, Vertical, and Functional Data Partitioning
▪ Increase Scalability
When divide data across multiple data partitions into
separate db servers, we can scale out the system without
worrying any hardware limits.
▪ Improve Availability
With Separating data across multiple servers, we protect our
systems for a single point of failures.
▪ Increase Performance (Query and operations)
Instead of querying whole database, system query only
smaller components.
▪ Improve Security
By storing sensitive and non-sensitive data into different
partitions.
▪ Improve Data Management https://www.redhat.com/architect/pros-and-cons-sharding
Due to divide tables and indexes with different partitions, its
more easy to manage small units and easy to maintenance.
Mehmet Ozkaya 437
Tinder System Design Example of
Database Sharding Pattern
▪ Tinder is very good example of Database Sharding Pattern.
▪ Tinder allows to match and meet other people who use the
application near you (around 160km) based on location.
▪ To find people near you very quickly and offer choices that
meet the criteria what you set.
▪ How Tinder match peoples who are near to each other ?
▪ Tinder segments users based on their location.
▪ This is called GeoSharding, that is, location-based
database sharding.
▪ Sharding by dividing the world map into boxes with their
locations and matches them in only into that box locations in
the world.
https://cassandra.apache.org/_/cassandra-basics.html
● Vue
● React
API Gateways
● Kong Gateway
● Express Gateway
Message Brokers
● Kafka
● RabbitMQ
Backend Microservices
● Java – Spring Boot
No-SQL Database Cloud No-SQL Database
● Cassandra – NoSQL Peer-to-Peer
● .Net – Asp.net ● Amazon DynamoDB
Partitioning
● Database Sharding Pattern: Increase Database
Drawbacks
● CAP Theorem: Data Consistency, Sacrifice Strong
several microservices ?
● Separate read and write operations at scale ?
Problems
● Cross-Service Queries with Complex JOIN
operations
● Read and write operations at scale
Solutions
● Microservices Data Query Pattern and Best
Practices
● Materialized View Pattern
several microservices ?
● Separate read and write operations at scale ?
Problems
● Cross-Service Queries with Complex JOIN
operations
● Read and write operations at scale
Solutions
● Microservices Data Query Pattern and Best
Practices
● Materialized View Pattern
Considerations
● Sync Communication: Use Service Aggregator Pattern
Solutions
● Materialized View Pattern
▪ Scalability
When we separate Read and Write databases, we can also
scale these separate databases independently. Read
databases follows denormalized data to perform complex join
queries.
▪ If application is read-incentive application, we can scale read
database more then write database.
▪ Query Performance
The read database includes denormalized data that reduce to
comlex and long-running join queries. Complex business
logic goes into the write database. Improves application
performance for all aspects.
▪ Maintability and Flexibility
Flexibility of system that is better evolve over time and not
affected to update commands and schema changes by
separating read and write concerns into different databases.
▪ Better implemented if we physically separate the read and Mehmet Ozkaya 467
write databases.
Drawbacks of CQRS
▪ Complexity
CQRS makes your system more complex design.
Strategically choose where we use and how we can separate
read and write database.
▪ Eventual Consistency
The read data may be stay old and not-updated for a
particular time. So the client could see old data even write
database updated, it will take some time to update read data
due to publish/subscribe mechanism.
▪ We should embrace the Eventual Consistency when using
CQRS, if your application required strong consistency than
CQRS is not good to apply.
● Vue
● React
API Gateways
● Kong Gateway
● Express Gateway
Message Brokers
● Kafka
● RabbitMQ
Backend Microservices
READ DB - No-SQL Database
● Java – Spring Boot WRITE DB - Relational Database
● Cassandra – NoSQL Peer-to-Peer
● .Net – Asp.net ● PostgreSQL
● MongoDB – NoSQL Document DB
● JS – NodeJS ● SQL Server
● Redis – NoSQL Key-Value Pair Mehmet Ozkaya 485
● Oracle
● Amazon DynamoDB, Azure CosmosDB
Way of Learning – The Course Flow
Drawbacks
● Increased Complexity, CQRS makes your system
Problems
● Distributed Transaction Management
Solutions
● Microservices Distributed Transaction Management
Problems
● Distributed Transaction Management
Solutions
● Microservices Distributed Transaction Management
▪ Saga pattern provides transaction management with using a sequence of local transactions of
microservices. And grouping these local transactions and sequentially invoking one by one.
▪ Each local transaction updates the database and publishes an event to trigger the next local transaction.
If one of the step is failed, than saga patterns trigger to rollback transactions.
▪ Each microservice communicates with the other microservices by exchanging events using a
message broker.
▪ Event-based approach allows for a more decentralized and flexible way to implement the SAGA
pattern, as each microservice can publish to events to the others in real-time.
▪ Choreography provides to coordinate sagas with applying publish-subscribe principles.
▪ Each microservices run its own local transaction, publishes events to message broker system and
trigger local transactions in other microservices.
▪ Orchestration-based SAGA pattern involves using a central orchestrator service to coordinate and
manage the individual sagas or microservices that make up a transaction.
▪ The orchestrator is responsible for initiating the transaction and ensuring that each saga performs its
step in the correct order.
▪ If any of the sagas fail to complete their step, the orchestrator can use the compensating transactions
to roll back the changes and restore the system to its original state.
▪ Orchestration provides to coordinate sagas with a centralized controller microservice that orchestrate
the saga workflow and invoke to execute local microservices transactions in sequentially.
mechanisms.
● Dual writes can be hard to detect and fix.
• Both becomes
dual writes
Solutions
● Transactional Outbox Pattern
Best Practice
● Use Red Hat Apache Kafka and CDC using Debezium in event-
driven applications.
● Use New databases like CockroachDB which has built-in
Mehmet Ozkaya 523
Change Data Capture feature.
Transactional Outbox Pattern
▪ Transaction performed before the event and the event written to the outbox table are part of the same
transaction.
▪ When a new order is added to the system, the process of adding the order and writing the Order_Created
event to the Outbox table is done in the same transaction to ensure the event is saved to the database.
▪ If one of the process is fail, this will rollback the whole operations with following ACID principles.
▪ The second step is to receive these events written to the Outbox table by an independent service and write
them to the Event bus. Another service listen and polls the Outbox table records and publish events.
● Creating new order record into order table and creating new
order_created event into outbox table are in the same transactions.
● Another service listen and polls the outbox table records and publish
events into separate processes.
● The current architecture required additional microservices that listen and
polls records from the outbox table.
Problems
● Reduces the performance and error-prone operations.
https://debezium.io/blog/2019/02/19/reliable-microservices-data-exchange-with-the-outbox-pattern/
Mehmet Ozkaya 533
CockroachDB for CDC and Outbox Pattern
https://medium.com/aws-lambda-serverless-developer-guide-with-hands/dynamodb-streams-using-aws-lambda-to-process-dynamodb-streams-for-change-data-
capture-2e3ab8df27ca
● Vue
● React
API Gateways
● Kong Gateway
● Express Gateway
● RabbitMQ
Backend Microservices
Log-based built-in CDC Database CDC – Open Source Tool
● Java – Spring Boot
● CockroachDB
● .Net – Asp.net ● Debezium
● Azure CosmosDB
● JS – NodeJS
● Amazon DynamoDB Streams Mehmet Ozkaya 541
Way of Learning – The Course Flow
transactions
● Real-time synchronization
Drawbacks
● Increased Complexity, Outbox Pattern and CDC
microservices
● Real-time processing
Solutions
● Event-driven architecture for microservices
Mehmet Ozkaya 545
Event-Driven
Microservices Architecture
Asynchronous communication, Decoupled communication
Event Hubs
Stream-Processing
Real-time processing
High volume events
Mehmet Ozkaya 546
Problem: Handle Millions of Events
Across Microservices
Considerations
● What if we have thousands of microservices that need to
microservices
● Real-time processing
Solutions
● Event-driven architecture for microservices
Mehmet Ozkaya 547
Introduction - Event-driven Architecture
▪ Real-time processing
Support real-time processing, as events are published and
consumed as soon as they occur. Need to react to events in
real-time, such as in systems that use CDC to track changes to
a database.
▪ High volume events
Well-suited to handling high volume events, as they can scale
horizontally by adding more event consumers as needed. Can
be scaled independently to handle increased load.
▪ Responsible business capability
Each service is responsible for a specific function or business
capability.
▪ Services communicate with each other by publishing and
subscribing to events, that make it easier to build and maintain
complex systems.
▪ Allows to work on different parts of the system in parallel
without having to worry about the impact on other components. Mehmet Ozkaya 550
Real-time Processing and High Volume Events
in Event-Driven Microservices Architecture
▪ Real-time processing
Real-time processing is achieved by using a message queue or event bus to publish and consume events
as they occur.
▪ When an event is generated, it is published to the message queue or event bus and made available to any
interested subscribers.
▪ Allows you to react to events in real-time, as they are published and consumed as soon as they occur.
▪ When need to perform real-time analytics or trigger actions based on changes to the data.
▪ High Volume Events
Using a message queue or event bus that can handle high volumes of events and distribute them to
multiple consumers.
▪ When you have a system that generates a large number of events, use a event bus to distribute those
events to multiple consumers, that can process events in parallel.
▪ Allows you to scale up the number of event consumers as needed to handle increased load.
▪ Event-driven microservices architectures to process events in real-time and scale to handle high volumes
of events.
Mehmet Ozkaya 551
Event Hubs and Event Streaming
in Event-Driven Microservices Architecture
▪ Event Hubs
Act as a central hub for data ingestion and distribution, allowing microservices to publish and subscribe to
data streams.
▪ Each microservice publish its data to an Event Hub. Other microservices can then subscribe to the Event
Hub and consume the data as needed.
▪ Communicate with each other in real-time, that needs to be highly reliable and scalable.
▪ Event Streaming
Allows you to capture and process a stream of events in real-time. Publish and consume events as they
occur.
▪ Allowing to build real-time data pipelines that can process and analyze data as it is being generated.
▪ One common use case for Event Hubs and event streaming in microservices architectures is real-time
analytics.
Frontend SPAs
● Angular
● Vue
● React
API Gateways
● Kong Gateway
● Express Gateway
Backend Microservices
● Java – Spring Boot
● .Net – Asp.net
● JS – NodeJS
Benefits
● Event Streaming
● Real-time Processing
● Resilience
Drawbacks
● Increased Complexity, event-driven makes your
Problems
● Slowliness and Low Performance Communication
performance
Solutions
● Distributed cache
Problems
● Slowliness and Low Performance Communication
performance
Solutions
● Distributed cache
▪ In-memory cache
Stores data in the main memory of a computer. In-memory caches are
typically the fastest type of cache, but the data is lost when the cache is
restarted or the machine is shut down.
▪ Disk cache
Stores data on a hard drive or solid-state drive. Disk caches are slower
than in-memory caches, but they can persist data.
▪ Distributed cache
Cache is distributed across multiple machines and is typically used in
distributed systems, such as microservices architectures.
▪ Distributed caches can improve the performance and scalability of a
system by allowing data to be stored and accessed from multiple
locations.
▪ Distributed caching is improving the performance by storing frequently accessed data in a cache that
can be quickly accessed from multiple locations.
▪ Microservices architectures are typically implement a distributed caching architecture:
▪ Improve the performance of individual services by storing frequently accessed data locally.
▪ Reducing the need to make expensive calls to a database or other external system.
▪ How can we increase the speed of the microservices ? With using Distributed Cache.
▪ Read-Through Strategy
When there is a cache miss, it loads missing data from the
database, populates the cache and returns it to the application.
▪ When a client requests data that is not found in the cache,
the cache will automatically retrieve the data from the
underlying database and store it in the cache for future
requests.
▪ Cache-aside strategy, when a client requests data that is not
found in the cache, the client is responsible for retrieving the
data from the database.
▪ Read-through cache strategy, when a client requests data
that is not found in the cache, the cache will automatically
retrieve the data from the database.
▪ Cache always stays consistent with the database.
▪ Write-Through Strategy
Update the cache whenever data is written to the backend
service. Cache always has the most up-to-date data, but it can
also result in a higher number of write operations.
▪ Instead of lazy-loading the data in the cache after a cache
miss, the cache is proactively updated immediately following
the primary database update.
▪ Data is first written to the cache and then to the database.
▪ Write-Back or Write-Behind Strategy
Delays updating the cache until a later time. This reduce the
number of write operations, but the cache may not have the
most up-to-date data.
▪ In Write-Through, the data written to the cache is
synchronously updated in the main database.
▪ In Write-Back or Write-Behind, the data written to the cache is
asynchronously updated in the main database.
Mehmet Ozkaya 575
Cache-Aside Pattern for Microservices
▪ (1) When a client needs to access data, it first checks to see if the
data is in the cache.
▪ (2) If the data is in the cache, the client retrieves it from the cache and
returns it to the caller.
▪ (3) If the data is not in the cache, the client retrieves it from the
database, stores it in the cache, and then returns it to the caller.
▪ Some of caching systems provide read-through and write-
through/write-behind operations. In these systems, client
application retrieves data over by the cache.
▪ For not supported Caches, it's the responsibility the applications
use the cache and update the cache if there is a cache-miss.
▪ Microservices good example to implement Cache-Aside pattern, it
is common to use a distributed cache that is shared across
multiple services.
Frontend SPAs
● Angular
● Vue
● React
API Gateways
● Kong Gateway
● Express Gateway
Backend Microservices
● Java – Spring Boot
● .Net – Asp.net
● JS – NodeJS
Benefits
● Improved performance; by storing frequently
Drawbacks
● Increased Complexity; cache can be complex
can be expensive
● Cache stampede Mehmet Ozkaya 585
Way of Learning – The Course Flow
Considerations
● Ensure continuity of service and minimize disruption
Solutions
● Containers and Orchestrators
Considerations
● Ensure continuity of service and minimize disruption
Solutions
● Containers and Orchestrators
▪ Isolation
Each microservice runs in its own container, provides isolation from the other
microservices and the host operating system.
▪ Scalability
Containers make it easy to scale microservices horizontally by simply running
more instances of a containerized microservice.
▪ Portability
Containers allow microservices to be easily deployed and run on any computer
or cloud platform that supports container runtime.
▪ Resiliency
Microservices are intended to be independently deployable and scalable. Using
containers in the deployment of microservices that can be quickly started and
stopped, increase the resiliency of the application.
1. Package each of microservices into a container image and push it to a container registry.
2. Then use the container orchestrator to deploy the microservices to a cluster of nodes.
3. Orchestrator will handle tasks such as scheduling containers onto nodes, monitoring the
health of the containers, and providing self-healing capabilities if a container fails.
▪ Automation
orchestrator can automate the deployment and management of your
microservices.
▪ Scalability
orchestrator can automatically scale your microservices up or down as needed to
meet changing demand.
▪ High availability
orchestrator can provide self-healing capabilities to ensure that your
microservices remain available even if individual containers fail.
▪ Improved resource utilization
Orchestrator can optimize the use of resources in your cluster.
▪ Portability
Containerized applications can be easily moved between different environments
and platforms.
▪ Security
orchestrators provide security features such as role-based access control and
network segmentation. Mehmet Ozkaya 600
What is Kubernetes ?
▪ Self-healing
Kubernetes can automatically restart containers that fail, ensuring that your
microservices remain available even if individual containers go down.
▪ Automatic scaling
Automatically scale your microservices up or down as needed to meet changing
demand, making it easier to handle sudden spikes in traffic.
▪ Load balancing
Automatically distribute incoming traffic across multiple instances of a
microservice.
▪ Declarative configuration
Allows to specify the desired state of your microservices using configuration files,
easy to automate the deployment and management of your applications.
https://kubernetes.io/docs/concepts/overview/components/
Mehmet Ozkaya 603
Kubernetes Components
▪ Pods
Pods are the smallest deployable units of computing, that you can create and
manage in Kubernetes. Pods stores and manage our docker containers.
▪ ReplicaSet
Maintain a stable set of replica Pods running at any given time. Used to
guarantee the availability of a specified number of identical Pods.
▪ Deployments
Provides declarative updates for Pods and ReplicaSets. Describe a desired
state in a Deployment, and the Deployment Controller changes the actual state
to the desired state at a controlled rate.
▪ Deployments are an abstraction of ReplicaSets, and ReplicaSets are an
abstaction of Pods.
▪ Pods should not created directly, if needed, Deployment objects should be
created.
▪ Service
Expose an application running on a set of Pods as a network service.
Kubernetes gives Pods their own IP addresses and a single DNS name for a
set of Pods, and can load-balance across them.
▪ ConfigMaps
API object used to store non-confidential data in key-value pairs. Pods can
consume ConfigMaps as environment variables, command-line arguments, or
as configuration files in a volume.
▪ Secrets
Store and manage sensitive information, such as passwords, OAuth tokens,
and ssh keys.
▪ Volumes
Persistent storage location that can be mounted into a pod. Volumes can be
used to store data that needs to persist across container restarts or be shared
between multiple containers in a pod.
▪ Increased complexity
Adding an additional layer of complexity to your deployment, more difficult
to understand and troubleshoot issues that arise.
▪ Increased resource usage
Running an additional container in a pod will increase the resource usage
of the pod.
▪ Decreased performance
Pod can potentially decrease the performance of the pod, as the sidecar
container will be competing for resources with the main container.
▪ Limited flexibility
Can be inflexible in some cases, as it requires that the main container
and the sidecar container run in the same pod.
▪ Blue-green deployment
Deploying updates to a new set of microservices (the "green" deployment), while the old version of the
microservices (the "blue" deployment) remains running.
▪ Rolling deployment
Deploying updates to a subset of the microservices at a time, and then rolling the updates out to the rest
of the microservices over time.
▪ Canary deployment
Deploying updates to a small subset of the microservices, and then gradually rolling the updates out to
the rest of the microservices over time.
▪ A/B testing
Deploying updates to a subset of the microservices, and then comparing the performance of the updated
microservices with the performance of the unmodified microservices.
▪ Infrastructure as a codebase that can be managed and versioned in the same way as application
code.
▪ IaC is to enable teams to manage their infrastructure in a more automated and repeatable way.
▪ IaC can be used to automate the process of deploying and managing the infrastructure needed to
run the microservices.
▪ I.e. define the infrastructure needed to run your microservices in a Kubernetes cluster, including the
pods, services, and other resources required.
▪ Terraform is a tool that allows you to define and manage infrastructure as code.
▪ Ansible is a tool that allows you to automate the deployment and management of infrastructure.
▪ They can be used to define the infrastructure needed to run your microservices in a Kubernetes
cluster.
▪ IaC is a useful tool for automating the process of deploying and managing the infrastructure.
▪ Teams can manage their infrastructure in a more repeatable and automated way, making it easier to
update and maintain their microservices over time.
Mehmet Ozkaya 618
Before Design – What we have in our design toolbox ? - Old
Architectures Patterns&Principles Microservices Caching Non-FR FR
• Microservices • The Database-per- • Caching Strategies • High Scalability • List products
Architecture Service Pattern • Filter products as per
• Cache Invalidation • High Availability
• Event-Driven • Polygot Persistence brand and categories
• Cache Hit - Cache Miss • Millions of Concurrent
Microservices
• Decompose services by User • Put products into the
Architecture • Cache-Aside Pattern shopping cart
scalability
• Independent • Apply coupon for
• The Scale Cube Deployable discounts
• Microservices • Technology agnostic • Checkout the shopping
Decomposition Pattern cart and create an order
• Data isolation
• Microservices • List my old orders and
• Resilience and Fault order items history
Communications Patterns
isolation
• Microservices Data
Management Patterns
• Event-Driven Architecture
• Microservices
Distributed Caching
Mehmet Ozkaya 619
Before Design – What we have in our design toolbox ? - New
Architectures Patterns&Principles Microservices Non-FR FR
• Microservices • The Database-per- Deployment • High Scalability • List products
Architecture Service Pattern, Polygot • Docker and Kubernetes • • Filter products as per
High Availability
Persistence, Decompose Architecture, Helm Charts brand and categories
• Event-Driven
services by scalability, • Millions of Concurrent
Microservices
The Scale Cube • Kubernetes Patterns; User • Put products into the
Architecture Sidecar Patterns, Service shopping cart
• Microservices Mesh Pattern • Independent • Apply coupon for
Decomposition Pattern Deployable discounts
• DevOps and CI/CD
• Microservices Pipelines • Technology agnostic • Checkout the shopping
Communications Patterns cart and create an order
• Deployment Strategies; • Data isolation
• Microservices Data Blue-green, Rolling, • List my old orders and
• Resilience and Fault order items history
Management Patterns Canary and A/B isolation
• Event-Driven Architecture Deployment.
• Microservices
Deployments with
Containers and Mehmet Ozkaya 620
Orchestrators
Microservices using Containers and Orchestrators
Frontend SPAs
● Angular
● Vue
● React
API Gateways
● Kong Gateway
● Express Gateway
Backend Microservices
● Java – Spring Boot
● .Net – Asp.net
● JS – NodeJS
Container Tools Orchestrator Tools Cloud Orchestrator Service Mesh IaC Cloud IaC
● Docker ● Kubernetes ● AKS, EKS, GKS ● Istio ● Terraform ● AWS
SCC
● Github
● Gitlab
IaC
● Terraform
● AWS
● Ansible
CodeBuild
Build ● AWS CDK
Registry Deployment Monitor
● Jenkins
● DockerHub ● Helm Charts ● Prometheus
● Maven
● ACR ● Ansible Scripts ● Datadog
● Gradle
● GCR ● Azure Devops ● Amazon CloudWatch
CodeBuild
Mehmet Ozkaya 624
How many concurrent request
can accommodate our design ?
Benefits
● Portability; Containers package applications and their
each microservice
● Scalability; Kubernetes can automatically scale
logging capabilities.
Drawbacks
● Complexity; complex to set up and manage.
performance
● Dependency on external tools; like Docker and
Considerations
● Deploy new features immediately without affecting the system
general behaviors
● System should recover from failures and provide ability of a
system to withstands.
● Architecture should be designed to be resilient
Solutions
● Microservices Resilience and Fault Tolerance
Distributed Tracing
Mehmet Ozkaya 629
● Microservices Health Monitoring
Microservices Resilience,
Observability and
Monitoring
Microservices Resilience and Fault Tolerance
Retry, Circuit-Breaker, Bulkhead Pattern
Microservices Observability with Distributed Logging and Distributed Tracing
Elastic Stack which includes Elasticsearch + Logstash + Kibana
Microservices Health Monitoring
Mehmet Ozkaya 630
Architecture Design – Vertical Considerations
Considerations
● Deploy new features immediately without affecting the system
general behaviors
● System should recover from failures and provide ability of a
system to withstands.
● Architecture should be designed to be resilient
Solutions
● Microservices Resilience and Fault Tolerance
Distributed Tracing
Mehmet Ozkaya 632
● Microservices Health Monitoring
What is Microservices Resiliency ?
▪ Retry Pattern
Retrying a request if it fails or times out. Retries can be
implemented at the client or the service level, to handle temporary
failures or disruptions.
▪ Circuit Breaker Pattern
Introducing a proxy or "circuit breaker" between a client and a
service. It will open the circuit and prevent further requests from
being sent to the service.
▪ Bulkhead Pattern
Partitioning a system into isolated components, or "bulkheads," to
prevent the failure of one component from affecting the others.
▪ Timeout Pattern
Should not wait for a service response for an indefinite amount of
time, throw an exception instead of waiting too long.
▪ Fallback Pattern
Providing an alternative behavior or response if a request fails or
times out. Mehmet Ozkaya 637
Retry Pattern
▪ Closed
The circuit breaker is not open and all requests are
executed.
▪ Open
The Circuit Breaker is open and it prevents the
application from repeatedly trying to execute an
operation while an error occurs.
▪ Half-Open
The Circuit Breaker executes a few operations to
identify if an error still occurs. If errors occur, then the
circuit breaker will be opened, if not it will be closed.
▪ Retry pattern only retry an operation in the expectation calls since it will get succeed.
▪ Circuit Breaker pattern is prevent broken communications from repeatedly trying to send request that is
mostly to fail.
https://speakerdeck.com/slok/resilience-patterns-server-edition?slide=33
• Microservices
Deployments with
Containers and Mehmet Ozkaya 663
Orchestrators
Before Design – What we have in our design toolbox ? - New
Architectures Patterns&Principles Microservices Non-FR FR
• Microservices • The Database-per- Resilience • High Scalability • List products
Architecture Service Pattern, Polygot • Resilience Patterns; • Filter products as per
• High Availability
Persistence, Decompose Retry, Circuit-Breaker, brand and categories
• Event-Driven
services by scalability, Bulkhead, Timeout, • Millions of Concurrent
Microservices
The Scale Cube User • Put products into the
Architecture Fallback Pattern shopping cart
• Microservices • Distributed Logging and • Independent • Apply coupon for
Decomposition Pattern Distributed Tracing Deployable discounts
• Microservices • Elastic Stack; • Technology agnostic • Checkout the shopping
Communications Patterns Elasticsearch + Logstash• cart and create an order
Data isolation
• Microservices Data + Kibana • List my old orders and
• Resilience and Fault order items history
Management Patterns • OpenTelemetry using isolation
• Event-Driven Architecture Zipkin
● React ● Bulkhead
● Express Gateway
Backend Microservices
● Java – Spring Boot
● .Net – Asp.net
● JS – NodeJS
● https://github1s.com/aspnetrun/run-aspnetcore-microservices
Mehmet Ozkaya 671
Alternative Link - https://github.com/mehmetozkaya/MicroservicesApp
Serverless Microservices
Architecture
AWS Event-driven Serverless Microservices using AWS Lambda, API Gateway,
EventBridge, SQS, DynamoDB and CDK for IaC
Mehmet Ozkaya
679