Chapter 8. Reactive persistence and event sourcing

 

This chapter covers

  • How to persist your domain models in a database
  • The two primary models of persistence: the CRUD model and the event-sourced model
  • The pros and cons of both models and how to select one for your domain model architecture
  • An almost complete implementation of an event-sourced domain model
  • How to implement a CRUD-based model functionally using a functional-to-relational framework

This chapter presents a different aspect of domain modeling: how to persist your domain model in an underlying database so that the storage is reliable, replayable, and queryable. You’ve likely heard about storage being reliable, thereby preventing data loss, and queryable, offering APIs so that you can use algebra (such as relational algebra) to query data from your database. This chapter focuses on two more aspects of persistence: traceability and replayability. In these cases, the data store also serves as an audit log and keeps a complete trace of all actions that have taken place on your data model. Just imagine the business value of such a storage mechanism that offers built-in traceability and auditability of your domain and data model!

Figure 8.1 shows a schematic of the chapter content. This guide can help you selectively choose your topics as you sail through the chapter.

Figure 8.1. The progression of this chapter’s sections

8.1. Persistence of domain models

8.2. Separation of concerns

8.2.1. The read and write models of persistence

8.2.2. Command Query Responsibility Segregation

8.3. Event sourcing (events as the ground truth)

8.3.1. Commands and events in an event-sourced domain model

8.3.2. Implementing CQRS and event sourcing

8.4. Implementing an event-sourced domain model (functionally)

8.4.1. Events as first-class entities

8.4.2. Commands as free monads over events

8.4.3. Interpreters—hideouts for all the interesting stuff

8.4.4. Projections—the read side model