13 Event sourcing: a functional approach to persistence

 

This chapter covers

  • Thinking functionally about persisted data
  • Event sourcing concepts and implementation
  • Architecture of event-sourced systems

In Chapter 12, you saw that in FP we avoid mutating state, especially global state. Did I mention that the database is also state, so it too should be immutable? What? Yes, didn’t you see this one coming? A database is, conceptually, just a data structure. Whether it’s stored in memory or on disk is ultimately just an implementation detail.

You saw in Chapter 12 how functional data structures, although immutable, can “evolve.” That is, you can create new “states” or new “views” of any given structure, which are built upon, but don’t alter, the original structure. This idea, which we explored with respect to objects, lists, and trees, naturally applies to in-memory data just as to stored data, and this is how our applications can represent change without mutation, even at the database level.

There are currently two approaches to this idea of append-only data storage:

  • Assertion-based—Treats the DB as an ever-growing collection of facts that are true at a given point in time
  • Event-based—Treats the DB as an ever-growing collection of events that occurred at given points in time

13.1 Thinking functionally about data storage

13.1.1 Why data storage should be append-only

13.1.2 Relax, and forget about storing state

13.2 Event sourcing basics

13.2.1 Representing events

13.2.2 Persisting events

13.2.3 Representing state

13.2.4 Representing state transitions

13.2.5 Reconstructing the current state from past events

13.3 Architecture of an event-sourced system

13.3.1 Handling commands

13.3.2 Handling events

13.3.3 Adding validation

13.3.4 Creating views of the data from events

13.4 Comparing different approaches to immutable storage

13.4.1 Datomic vs. Event Store

13.4.2 How event-driven is your domain?

13.5 Summary