14
Command Query Responsibility Segregation Jonathan Oliver

CQRS: An Introduction for Beginners

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: CQRS: An Introduction for Beginners

Command QueryResponsibility Segregation

Jonathan Oliver

Page 2: CQRS: An Introduction for Beginners

Who Cares?

“This time, it’s going to be different. Trust me.”

“Doctor, it hurts when I do that.”

Why?

UI

Services / Caching

Business Logic

DAL

Database

Page 3: CQRS: An Introduction for Beginners

A Question of Perspective

Why are we doing this?

It’s a “Best Practice”.

The way it’s always been done.

Page 4: CQRS: An Introduction for Beginners

A Few Problems

Bottlenecks Caching

Scalability Translation code Impedance mismatch Race conditions Stale data

UI

Services / Caching

Business Logic

DAL

Database

Page 5: CQRS: An Introduction for Beginners

Stale Data?

Get data Get data

Update data

Stale data

Page 6: CQRS: An Introduction for Beginners

Queries

If it’s stale anyway…

List of Customers…………………….…………………….…………………….…………………….…………………….

(from 10 minutes ago)

Page 7: CQRS: An Introduction for Beginners

A Persistent View Model

Read only. Stored in structure used by view.

Persistent View Model

Query

SELECT * FROM Table WHERE ID = …

Page 8: CQRS: An Introduction for Beginners

That’s Blasphemy!

It’s the simplest thing that could possibly work.

Testability? Maintainability? Security?

Data already shown over the web. It’s already in your cache on the web

tier. Role-based SELECTs.

Page 9: CQRS: An Introduction for Beginners

Commands and User Input

What is the user telling us?

Do we even know?

How?

Task-based UIs vs. CRUD-based UIs.

Capture user intent explicitly.

Page 10: CQRS: An Introduction for Beginners

Validation and Business Rules

Pre-validation from view model.

Validation: Is this command complete? String lengths Required fields Regex, etc.

Business Rules: Can I do what the user wants? Where is the source of truth?

Page 11: CQRS: An Introduction for Beginners

Good Commands

Validated on client.

Revalidated on server.

Reply can be asynchronous: Amazon

Page 12: CQRS: An Introduction for Beginners

CQRS

Image courtesy Udi Dahan

Page 13: CQRS: An Introduction for Beginners

Service Layer

Transaction Script. Active Record / Table Module. Domain Model.

No Getters/Setters

Transactional. Separate database from queries. The “source of truth”.

Page 14: CQRS: An Introduction for Beginners

Questions?