What is event sourcing?

Event sourcing is a strategy that allows developers to model and capture data by thinking primarily in terms of events rather than the final data structure that they wish to encapsulate. This is very different to the more conventional CRUD (Create, Read, Update, and Delete) approach.

Let's consider a theoretical scenario whereby a user wishes to capture a candidate's data for a recruitment CRM they are building. Using the traditional CRUD approach, a developer might capture essential data such as forename, surname, date of birth, email address, and contact number. They would then take this data and persist it straight to a database of their choosing.

Traditional CRUD Approach

sequenceDiagram participant User participant App as CRM Application participant DB as Database (Current State) User->>App: Submits Signup Form (John Doe) App->>DB: INSERT INTO candidates (forename, surname, ...) Note over DB: Record exists with current data User->>App: Changes Surname (John Smith) App->>DB: UPDATE candidates SET surname = 'Smith' WHERE id = 1 Note over DB: Old name 'Doe' is lost forever

In event sourcing, the data would be modelled in the context of an event, for example 'candidate-signed-up'. That event would hold all the same forementioned properties. So far there is little difference from the CRUD approach. The event would then be stored in an event library (multiple implementations exist for this purpose, EventSourcerer being one).

Event Sourcing Approach

sequenceDiagram participant User participant App as CRM Application participant ES as Event Store (History) User->>App: Submits Signup Form (John Doe) App->>ES: Append: CandidateSignedUp (John Doe) User->>App: Changes Surname (John Smith) App->>ES: Append: SurnameChanged (John Smith) Note over ES: Both events are preserved Note over App: Replay events to find ALL surnames

Let's now imagine that the candidate's name changes after a few years of being registered with the recruitment CRM. An admin user then wishes to search by surname for all positions that the candidate has applied for since they registered. Under the traditional CRUD system the recruitment CRM would only hold the users' current surname (of course the recruitment CRM may have planned for such eventualities and have a strategy in place but it is not always easy to predict such eventualities) and therefore only vacancies applied for since the user changed their name would be returned. With event sourcing, however, it would be possible to loop through all events and discover all surnames connected to the candidate, and therefore return all vacancies applied for under multiple surnames.