Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Валентин Кононов «CQRS и Event Sourcing для Bac...

Валентин Кононов «CQRS и Event Sourcing для Backend-систем»

CQRS является достаточно известным подходом, но из-за некоторой сложности, на первый взгляд, мало кто его применял в реальных проектах. Мы поговорим о теоретической составляющей данного подхода и примерах из жизни, где его применение оправдано. Зачастую данных подход хорошо сочетается с другим принципом — Event Sourcing, который мы тоже затронем.

Доклад будет посвящен описанию подходов и сфере применения. Специфических знаний конкретного языка программирования или фреймворков для посещения данного доклада не требуется. Знания применимы независимо от платформы. Выступление и презентация вдохновлены известным .NET тренером и автором многих книг — Дино Эспозито, воркшоп которого Валентин посетил в Минске.

DotNetRu

June 23, 2018
Tweet

More Decks by DotNetRu

Other Decks in Programming

Transcript

  1. CQRS Meaning • Command • Query • Responsibility • Segregation

    Presentation Layer (Views, Inputs, Controllers) Infrastructure Layer (Repository, ORM, DataBase) Application Layer (App Service) Domain Layer (Domain Service, Event Bus, Message Bus, ...) Query Handler Data Access DTO Command Query
  2. CQRS Concept Command = workflow, that alters the current state

    of the system Query = workflow, that reports a view of the current state of the system
  3. Money Transaction Sample • User performs money transfer • Most

    probably he has money • We can perform transaction and report success • In case of error - rollback later
  4. CQRS Diagram Canonical Layered Architecture Presentation Layer Application Layer Domain

    Layer Infrastructure Layer CQRS Layered Architecture Presentation Layer Infrastructure Layer Application Layer Domain Layer Data Access + DTO
  5. CQRS Benefits - Divide et Impera • Distinct Optimization •

    Scalability Potential - both technical and Teams • Simplified Design and Less complexity of changes
  6. CQRS - In simple code sample private int x; public

    int increment_and_return_x() { lock x; x = x + 1; int x_copy = x; unlock x; return x_copy; } private int x; public int value() { return x; } void increment_x() { x = x + 1; } Regular Code CQRS Code
  7. Sample Solution Schema - In Visual Studio you can setup

    projects like this App.CommandStack App.Infrastructure App.QueryStack APP.CQRS
  8. Event Sourcing • In the real world we observe events

    • In software, we tend to write models
  9. Event Sourcing - All Changes to the Application are saved

    as a sequence of events - You don’t miss a thing. For the entire lifetime of the system
  10. Event Sourcing Schema Application Write Interface Event Handler Event Store

    Application State Event Queue Read Service Application Read Interface
  11. Read Model Artificially created data model that offers a business-specific

    view of the current state of the system. Event 1 Event 2 Event ... Event N Snapshot Event N+1 Event N+2 Event N+3
  12. Lower abstraction layer of data • Events are immutable. You

    don’t miss a thing • Events can be replicated • Replaying the event doesn’t require to repeat the behavior • Track everything that happened
  13. About Scalability • Event storage allows to implement any amount

    of new features and services based on the same data • Consistency - minimal set of rules allows to keep your data consistent • Can serve as environment for other platforms • Works well with microservices architecture
  14. Technically - how to save events NOSQL Data Storage Special

    Event Store JSON Friendly Relational DB Raven DB Mongo DB Cosmos DB ... EventStore NEventStore SQL Server 2016 PostgreSQL ... Backendless Stores FireBase Parse ...
  15. Event Sourcing together with CQRS Command Pushed Workflow Execution Event

    Store Application State App State Update Event Saved New Event Triggered API Call Message Generated Notification Sent ...
  16. Projects based on these approaches 1. Sample of money transfer

    for CQRS 2. Sample of Social Networks 3. Sample of Trucks Telematic project with event sourcing 4. Sample of Reporting for high load once a year for CQRS 5. Sample of Electric Station for event sourcing
  17. Social Network Sample • When user posts something - app

    produces number of work items ◦ Add data to event storage ◦ Add view storage for user ◦ Notify users (in browsers, push notifications….) ◦ Update search indexes... Web Application Application Service Search DataBase ... Cache Jobs Message Queue ... ...
  18. Trucks Telematics • Eco System based on real time data

    from trucks ◦ Speed, location, temperature, … ◦ Engine turned on / off, … ◦ Diagnostic messages • Dashboard with average statistics and ability to change level of details • Reporting Web Dashboard Read Service Data Aggregation Event Store Truck Sensor Event Write Service
  19. • System to enter finance data and see reports for

    government • Data is entered all the time, but at the end of finance year application load increases 10 times • Reporting should be available immediately Finance Year Reporting Reporting Reporting Service SQL Server Application Service Web Application MongoDB
  20. • Real app data - events from turbines, solar panels.

    Each impulse of data - event. • No user interface to enter data • No presentation layer to observe data • Workers need to see some data model Electric Station