Download - CQRS: An Introduction for Beginners
Command QueryResponsibility Segregation
Jonathan Oliver
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
A Question of Perspective
Why are we doing this?
It’s a “Best Practice”.
The way it’s always been done.
A Few Problems
Bottlenecks Caching
Scalability Translation code Impedance mismatch Race conditions Stale data
UI
Services / Caching
Business Logic
DAL
Database
Stale Data?
Get data Get data
Update data
Stale data
Queries
If it’s stale anyway…
List of Customers…………………….…………………….…………………….…………………….…………………….
(from 10 minutes ago)
A Persistent View Model
Read only. Stored in structure used by view.
Persistent View Model
Query
SELECT * FROM Table WHERE ID = …
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.
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.
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?
Good Commands
Validated on client.
Revalidated on server.
Reply can be asynchronous: Amazon
CQRS
Image courtesy Udi Dahan
Service Layer
Transaction Script. Active Record / Table Module. Domain Model.
No Getters/Setters
Transactional. Separate database from queries. The “source of truth”.
Questions?