Transcript
Page 1: CQRS recipes or how to cook your architecture

CQRS recipes or how to cook your architecture

@tjaskula

Page 2: CQRS recipes or how to cook your architecture

But before we dive into CQRS recipes…

…we have to understand basic layered ones

Page 3: CQRS recipes or how to cook your architecture

Maslow pyramid in meal recipesNot official, just my own trip

Culinary art

Fine food

Home cooking

Fast food and frozen food

Basic ingredients like milk, bread, meat

Page 4: CQRS recipes or how to cook your architecture

Hey! How this relates to architecture mate?

Page 5: CQRS recipes or how to cook your architecture

Maslow architecture pyramid?This should somehow map

?

?

?

?

?

Culinary art

Fine food

Home cooking

Fast food and frozen food

Basic ingredients like milk, bread, meat

Page 6: CQRS recipes or how to cook your architecture

But first let’s tell a little story…

…of one e-commerce application that I’ve learnt so hard

Page 7: CQRS recipes or how to cook your architecture

Once upon a time… a marketing team came in

…to announce to developers what they have sold

Page 8: CQRS recipes or how to cook your architecture

“We need an e-commerce portal. Now!”

“Do it fast”

“We need every feature Orders, Product catalog, Suppliers”

Page 9: CQRS recipes or how to cook your architecture

Development has started…

Page 10: CQRS recipes or how to cook your architecture

In progress…

Page 11: CQRS recipes or how to cook your architecture

…Then the developer has came after a while…

Page 12: CQRS recipes or how to cook your architecture

E-Commerce portal architecture

UI

Domain

DAL

DB

Page 13: CQRS recipes or how to cook your architecture

Another feature was asked by the business…

Page 14: CQRS recipes or how to cook your architecture

But developers just…

Page 15: CQRS recipes or how to cook your architecture

It will take another year. Because we’ve built a…

Page 16: CQRS recipes or how to cook your architecture

“We need to refactor. Business want’s more features…”

How to refactor a monolith?

Page 17: CQRS recipes or how to cook your architecture

To decouple every component, you have.

Evolve domainindependently, it should.

Handle business needs easier, you will.

Page 18: CQRS recipes or how to cook your architecture

Decouple components

Handle business logic in isolated domain

We have to think it over, but for now let’s wrap up what we’ve learnt

Write unit test because every change is a breaking one

Page 19: CQRS recipes or how to cook your architecture

Lesson learnt 1

Simple architecture, does not scale, hard to maintain, often monolithic

Recipe 1:Basic layered architecture

Page 20: CQRS recipes or how to cook your architecture

Recipe 1

Basic layered architecture

Ingredients

Basic coding skillsSome infrastructure pieces (DB, etc.)

Client reviews

• Can be set up very quickly• Easy to understand• No need for experienced developers. Juniors can make it

• Leads quickly to unmaintainable monolith code blocks• Not easily evolvable for quickly changing business requirements• Not scalable• Not performent if charge gets bigger• Not testable. You’d better have end-to-end integration tests

Difficulty:

Time: from 25 min to infinityPreparation:Just throw basic code skills in. Mix it up with a database and UI and everything will be fine…or not…

UI

Domain

DAL

DB

Page 21: CQRS recipes or how to cook your architecture

Where we’ve been?

Ah yeah…DECOUPLING stuff

Page 22: CQRS recipes or how to cook your architecture

Then this came in

Let’s decouple ourselves from DB

Page 23: CQRS recipes or how to cook your architecture

And decouple us from everything else…

IoC container FTW!

Page 24: CQRS recipes or how to cook your architecture

And…

Page 25: CQRS recipes or how to cook your architecture

And…

Page 26: CQRS recipes or how to cook your architecture

Business ask more futures for Orders, Suppliers, stuff…

Page 27: CQRS recipes or how to cook your architecture

UI

OrderViewModel

Order

OrderController

OrderMapper IOrderMapper

SqlOrderRepository IOrderRepository

DB

Pre

sen

tati

on

Do

mai

nIn

fras

tru

ctu

re

Architecture v2

Page 28: CQRS recipes or how to cook your architecture

What's the problem with n-layered architectures?

Page 29: CQRS recipes or how to cook your architecture

What's the problem with n-layered architectures ?

Reused Abstraction Principle

VIOLATED

Page 30: CQRS recipes or how to cook your architecture

Over time, more features, more pain…

Page 31: CQRS recipes or how to cook your architecture

Because of…

public class OrderController {

public OrderController (IOrderValidator order validator,IOrderMapper orderMapper,IOrderRepository orderRepositoryISupplierRepository supplierRepositoryIAuthorizationFactory authorizationFactory,IUnitOfWork unitOfWork,IUserFactory userFactoryISession session,ILogger logger,IOrderCache orderCache) {

}}

Page 32: CQRS recipes or how to cook your architecture

And because developers spent their time on…

Page 33: CQRS recipes or how to cook your architecture

It seems that after a while we have still a monolith

Page 34: CQRS recipes or how to cook your architecture

But decoupled

Page 35: CQRS recipes or how to cook your architecture

We need more data on UI and different views per user…

Page 36: CQRS recipes or how to cook your architecture

But our model doesn’t support it

Every time we add a new view our model is broken…

Views are slower. Users complain…

Page 37: CQRS recipes or how to cook your architecture

Your reads from writes separate. Herh herh herh.

CQRS, you will do !

Page 38: CQRS recipes or how to cook your architecture

We have to think about it…

Time to wrap up…

Page 39: CQRS recipes or how to cook your architecture

Lesson learnt 2

Domain centric, refactorable and evolvable

Simple architecture, does not scale, hard to maintain, often monolithic

Recipe 1:Basic layered architecture

Recipe 2:n-layered architecture with DI

Page 40: CQRS recipes or how to cook your architecture

Recipe 2

N-layered architecture with DI

Ingredients

OOP skillsWith SOLID principles would be event betterORMs and IOCsSome infrastructure pieces (DB, etc.)

Client reviews

• Can be set up rather quickly• Easy to understand• Can be tested

• Can lead to unmaintainable monolith code blocks• Not easily evolvable for quickly changing business requirements• Not scalable• Not performent if charge gets bigger

Difficulty:

Time: reasonablePreparation:One must know OOP concepts and the best would be also to be aware of SOLID principles…

UI

OrderViewModel

Order

OrderController

OrderMapper IOrderMapper

SqlOrderRepository

IOrderRepository

DB

Page 41: CQRS recipes or how to cook your architecture

Where we’ve been?

Ah yeah…CQRS stuff

Page 42: CQRS recipes or how to cook your architecture

What is CQRS?

CQS applied to architecture = CQRS

Split Read from Writes

Page 43: CQRS recipes or how to cook your architecture

UI

Domain

Repository

DB Write DB Read

Read Model Application service

Command Query

Architecture v3

Page 44: CQRS recipes or how to cook your architecture

Command

UI

Domain

Repository

DB Write

Read Model Application service

DB Read denormalized

Query

Architecture v3 bis

Page 45: CQRS recipes or how to cook your architecture

Wow, the speed of views has increased

We can scale up read and write side independently

Easy to handle more business request about views and queries in denormalized DB

Page 46: CQRS recipes or how to cook your architecture

Even of it’s better we still have problems

Why we have impacts between different business lines?

Why it takes so much time for a new feature? And we always don’t get exactly what we want. There is always a confusion.

Page 47: CQRS recipes or how to cook your architecture

Integration inside of the business

CRUD events ?CQRS not a top level architecture

Page 48: CQRS recipes or how to cook your architecture

Composite UI

UI

Data Access Layer

Web / Application Tier

Background server Tier

Storage Tier

DDD layeredapplication

Writemodel

Readmodel

Legacy application

Domain A Domain B Domain C Domain D

CRUD architecture (simple non-core domain

functionality)

DDD (core domainfunctionality)

CQRS (core domainfunctionality)

Legacy subsystem

Page 49: CQRS recipes or how to cook your architecture

How to know where to put the effort?

Page 50: CQRS recipes or how to cook your architecture

What is the strategic advantage of my company?

Page 51: CQRS recipes or how to cook your architecture

Order management system is our strategic goal…

Page 52: CQRS recipes or how to cook your architecture

Great then we know where to put our effort…

Page 53: CQRS recipes or how to cook your architecture

But how do we find the best model for a business…

Page 54: CQRS recipes or how to cook your architecture

To them about events talk.

Find it meaningful, will they. Yeesssssss.

Page 55: CQRS recipes or how to cook your architecture

The quest has started

Event Storming = Domain Discovery Tool

source : Brandolini http://bit.ly/1s1dwoB

Page 56: CQRS recipes or how to cook your architecture

Events, that’s the way we think about it!

Page 57: CQRS recipes or how to cook your architecture

From events, to aggregates…It’s DDD!

Page 58: CQRS recipes or how to cook your architecture

Domain Driven DesignIt’s much more than just commands and events

• Ubiquitous Language

• Bounded Context

• Context Map

• Domain Event

• Aggregates

Page 59: CQRS recipes or how to cook your architecture

We need a new feature concert ticket sell

Page 60: CQRS recipes or how to cook your architecture

Done!

Page 61: CQRS recipes or how to cook your architecture

System is unusable users are blocked!!!

Page 62: CQRS recipes or how to cook your architecture

Ah no, what to do?

Page 63: CQRS recipes or how to cook your architecture

Express business intent in commands and facts in events, you will.

Make events asynchronous, you will. Herh herh herh.

Page 64: CQRS recipes or how to cook your architecture

We have to think about it…

Time to wrap up…

Page 65: CQRS recipes or how to cook your architecture

Lesson learnt 3

Decoupled and easy to integrate with external

systems

Domain centric, refactorableand evolvable

Simple architecture, does not scale, hard to maintain, often monolithic

Recipe 1:Basic layered architecture

Recipe 2:n-layered architecture with DI

Recipe 3:Hexagonal with basic CQRS

Page 66: CQRS recipes or how to cook your architecture

Recipe 3

Basic CQRS

Ingredients

OOP skillsSOLID principlesDomain Driven Design would be a big advantage

Client reviews

• Scale out read from writes independently• Can handle more business request about queries• More maintainable code• Even easier to test

•Users still can be blocked read and write are synchronous• Not so performent for big charges

Difficulty:

Time: mid-termPreparation:Establish a ubiquitous language with your domain experts and express it in the code

UI

Domain

Repository

DB Write

Read Model

Application service

DB Rea

ddenormalized

Page 67: CQRS recipes or how to cook your architecture

Where we’ve been?

Ah yeah commands and events…asynchronous

Page 68: CQRS recipes or how to cook your architecture

Command, it’s business intent like “Place Order”

Event, it’s business immutable fact like “OrderPlaced”

Page 69: CQRS recipes or how to cook your architecture

Architecture v4

Domain Repository

DB Write

Read Model Application service

DB Read

UI

Command Handler

Command Bus

Event Bus

Read model generator

Another context application

Command

Event

Dependency

Page 70: CQRS recipes or how to cook your architecture

Domain Repository

DB Write

Read Model Application service

DB Read DB Write

Read Model Application service

DB Read

Command Handler

Command Bus

Event Bus

Read model generator

ACL

Command Handler

Domain RepositoryRead model generator

UI

Command

Event

Dependency

Architecture v4’

Page 71: CQRS recipes or how to cook your architecture

Domain Repository

DB Write

Read Model Application service

DB Read DB Write

Application service

UI

Command Handler

Command Bus

Event Bus

Read model generator

ACL

Command Handler

Domain Repository

Command

Event

Dependency

Architecture v4’’

Page 72: CQRS recipes or how to cook your architecture

But there is a trap. Views are not refreshed immediately

Page 73: CQRS recipes or how to cook your architecture

CAP Theorem*CQRS Ingredients

Consistency:A read sees all previously completed writes

Availability:Reads and writes always succeed

Partition tolerance:Guaranteed properties are maintained even when network failures prevent some machines from communicating with others

* Eric Brewer

A system can be either CP, AP. CA is not coherent.

Page 74: CQRS recipes or how to cook your architecture

CAP TheoremCQRS Ingredients

CP AP

Node 1 Node 2 Node 1 Node 2

Data Data Data Data

Page 75: CQRS recipes or how to cook your architecture

Eventual ConsistencyCQRS Ingredients

« A key benefit of embracing eventual consistency is to remove the requirement for using distributed transactions »

Users deal every day with Eventual Consistency

Page 76: CQRS recipes or how to cook your architecture

But there is still a trap with event synchronization

Page 77: CQRS recipes or how to cook your architecture

Write side Read side

UI

Write Model

DB Write

Read Model

DB Read

Update write sidedata store Update read side

data store

Read data

Transaction Scope

Page 78: CQRS recipes or how to cook your architecture

Write side Read side

UI

Write Model

DB Write

Read Model

DB Read

Update write sidedata store

Send message to update read sidedata store

Read data

Transaction Scope

Event BusReliable messaging

Page 79: CQRS recipes or how to cook your architecture

Write side Read side

UI

Write Model

DB Write

Read Model

DB Read

Update write sidedata store

Send message to update read sidedata store

Read data

Transaction Scope

Event BusReliable messaging

Page 80: CQRS recipes or how to cook your architecture

I would like to know if user before placing an Order removes Items if we propose them more useful articles with our recommendation system

Page 81: CQRS recipes or how to cook your architecture

That’s a tricky question. We don’t have a history.

Page 82: CQRS recipes or how to cook your architecture

All you need, you have.Use your events, you will. Yeesssssss.

Page 83: CQRS recipes or how to cook your architecture

We have to think about it…

Time to wrap up…

Page 84: CQRS recipes or how to cook your architecture

Lesson learnt 4

Easily scalable and

preferment

Decoupled and easy to integrate with external

systems

Domain centric, refactorableand evolvable

Simple architecture, does not scale, hard to maintain, often monolithic

Recipe 1:Basic layered architecture

Recipe 2:n-layered architecture with DI

Recipe 3:Hexagonal with basic CQRS

Recipe 4:Hexagonal’ish with CQRS + DDD

Page 85: CQRS recipes or how to cook your architecture

Recipe 4

Basic CQRS + DDD + Async

Ingredients

Good OOP skillsSOLID principlesDomain Driven Design modelingGood knowledge of messaging infrastructure

Client reviews

• Handles concurrent domains• Scale out read from writes independently• Can handle more business request about queries• Business process explicit• Even easier to test

• Many moving parts• Sometimes integration points between systems are harder to grasp• Bad things can happen if no integration events command are stored

Difficulty:

Time: long termPreparation:Gather business intent in form of Commands, map it to business events and synchronize everything async.

DomainReposito

ry

DB Write

Read Model Application

service

DB Read

DB Write

Application service

UI

Command Handler

Command Bus

Event Bus

Read model

generator

ACL

Command Handler

DomainReposito

ry

Page 86: CQRS recipes or how to cook your architecture

Where we’ve been?

Ah yeah storing events…

Page 87: CQRS recipes or how to cook your architecture

For legal thing, we would like an audit log

Page 88: CQRS recipes or how to cook your architecture

If we got a time machine…

Page 89: CQRS recipes or how to cook your architecture

Yes you have it. Events = facts

Page 90: CQRS recipes or how to cook your architecture

Event SourcingCQRS Ingredients

Event as a storage mechanism

OrderOrder line

Item

Shipping information

Order Created

Added 2 items 245

Added 3 items 455

Removed 2 items 245

Added shipping info

Order placed

Page 91: CQRS recipes or how to cook your architecture

Event Sourcing

Rolling snapshot

Order Created

Added 2 items 245

Added 3 items 455

Removed 2 items 245

Added shipping info

Order placed

Snapshot

Put on stack Added 3 items 455

Removed 2 items 245

Added shipping info

Order placed

Snapshot

Page 92: CQRS recipes or how to cook your architecture

Domain

Event Store

Read Model Application service

DB Read

UI

Command Handler

Command Bus

Event Bus

Read model generator

Another context application

Command

Event

Dependency

Page 93: CQRS recipes or how to cook your architecture

Domain

Event Store

Read Model Application service

DB Read DB Write

Read Model Application service

DB Read

UI

Command Handler

Command Bus

Event Bus

Read model generator

ACL

Command Handler

Domain RepositoryRead model generator

Command

Event

Dependency

Page 94: CQRS recipes or how to cook your architecture

Domain

Event Store

Read Model Application service

UI

Command Handler

Command Bus

Event Bus

Another context application

Command

Event

Dependency

Page 95: CQRS recipes or how to cook your architecture

Our system seems to be on the right track now !

Page 96: CQRS recipes or how to cook your architecture

Lesson learn 5

Resilient

Easily scalable and

preferment

Decoupled and easy to integrate with external

systems

Domain centric, refactorableand evolvable

Simple architecture, does not scale, hard to maintain, often monolithic

Recipe 1:Basic layered architecture

Recipe 2:n-layered architecture with DI

Recipe 3:Hexagonal with basic CQRS

Recipe 4:Hexagonal’ish with CQRS + DDD

Recipe 5:Hexagonal’ish with CQRS + DDD + ES

Page 97: CQRS recipes or how to cook your architecture

Recipe 5

Basic CQRS + DDD + ES

Ingredients

Good OOP skillsSOLID principlesDomain Driven Design modelingGood knowledge of messaging infrastructureFunctional thinking

Client reviews

• Handles concurrent domains• Scale out read from writes independently• Can handle more business request about queries• Business process explicit• Audit log, testing and infinite business views on data

• Many moving parts• Sometimes integration points between systems are harder to grasp• Bad things can happen if no integration events command are stored

Difficulty:

Time: long termPreparation:Make your events talk.

Domain

Event Store

Read Model Application

service

DB Read

DB Write

Read Model Application

service

DB Read

UI

Command Handler

Command Bus

Event Bus

Read model

generator

ACL

Command Handler

DomainRepositor

y

Read model

generator

Page 98: CQRS recipes or how to cook your architecture

Maslow architecture pyramidNot official, just my own trip

Resilient

Easily scalable and

preferment

Decoupled and easy to integrate with external

systems

Domain centric, refactorableand evolvable

Simple architecture, does not scale, hard to maintain, often monolithic

Culinary art

Fine food

Home cooking

Fast food and frozen food

Basic ingredients like milk, bread, meat

Page 99: CQRS recipes or how to cook your architecture

What CQRS is not?CQRS Basics/From CQS to CQRS

Page 100: CQRS recipes or how to cook your architecture

Is CQRS for me?CQRS Basics/From CQS to CQRS

What kind of problem do I try to solve ?

• Collaborative domain• Locking the data without blocking the user

• Read data scalability

• Performance optimization

• Complex workflows / Temporal data / Stale data

Page 101: CQRS recipes or how to cook your architecture

There is more

Aggregates

• Validation

• Uniqueness checking

• Existence checking

• Replaying of events (Event Sourced)

Long running workflows

Optimization

Page 102: CQRS recipes or how to cook your architecture

Long running workflowsCQRS Deep Dive Cooking

How do I know if I need one?

Difference between Saga and Process Manager?

Page 103: CQRS recipes or how to cook your architecture

Client

Order ProcessManager

OrderAggregate

Stock Aggregate

PaymentAggregate

2. O

rder

Pla

ced

3. Make reservation

4. ItemsReserved

5. M

ake

pay

men

t

6. P

aym

entA

ccep

ted

7. OrderConfirmed

7. O

rder

Co

nfi

rmed

7. OrderConfirmed

Page 104: CQRS recipes or how to cook your architecture

Questions ?


Top Related