Event sourcing – data integrity
Before going directly onto the theme of event sourcing, it is necessary to understand the functioning of most standard applications.
Whenever we run the command UPDATE
in the database, we perform a modification to our current representation in the database. With that, whenever we do a query on the database, we seek the current state of a record. This behavior is called state mutation. Let's use an example to make it clearer.
State mutation
Suppose we have a table responsible for administering the access level of a user. The table is composed as follows:
|
|
|
|
|
|
|
|
As we look at the preceding table, we see that the user John Doe
is an administrator and this status was applied by Manager1
. After a period of time, it was found that John Doe could never have been the admin of the application and an UPDATE
is performed on this row in the table:
UPDATE status_user set status='normal_user', user_manager='Manage2' WHERE ID=1;
This change results in some modifications in line with ID = 1
:
|
|
|
|
|
|
|
|
In this case, Manager2
was responsible for the change in the status of the user. The current status of the user John Doe
is normal_user
, but what was the previous status? Who was responsible for making John Doe an application administrator for some period of time?
The default behavior adopted to record changes in the database does not allow us to know the trajectory of a record within the application—we always know only the current state of the registry. To supply to this kind of need, I want to get to know the entire history of a record that enters event sourcing.
Understanding event sourcing
The idea of event sourcing is a little different. Each change in the current state of your database would be a new event in a stream that only allows inclusion. Each update on the table would generate a new line, the change of status. If you have changed to an incorrect status, a new line would be generated by correcting this status. So, we'd have all the changes until you reach the current time of permission for the user.
From the beginning, in the status_user
table using the concept of event sourcing, the records would be as follows:
|
|
|
|
|
|
|
|
|
|
|
|
If a new status change is applied to the user John Doe
, a new line would be generated by keeping track of the changes. Event sourcing uses the append only model for database records.
Event sourcing has positives and negatives. Among the positive points are the historical maintenance records, while negatives include exponential growth in the database records' editing operations. For this reason, it is very common to see event sourcing being used with CQRS, precisely, not to encumber the searches in the database due to a large number of the same record.