When you want code works under race conditions, commonly developers uses Optimistic concurrency control (OCC). From Wikipedia:
...before committing, each transaction verifies that no other transaction has modified the data it has read. If the check reveals conflicting modifications, the committing transaction rolls back...
An approach to implement OCC is checking a version
of the data to be modified. If the version differs, then other transactions have modified the data and the it's up to the application to decide how it should resolve the conflict (reattempt, notify user...).
A draft would be as following:
class Repository
{
public class save($data)
{
$currentVersion = $data->version;
$data->version = $currentVersion + 1;
$result = $this->db->update($data, [
'id' => $data->id,
'version' => $currentVersion
]);
if (1 === $result) {
// everything ok
} else {
// conflict!
}
}
}
My question is, as in EventSourcing
we only append all events that occurs in the domain, we can't no longer use this approach to implement OCC. Which are other approaches to keep OOC while using EventSourcing?
An option that could works, it's lookup for conflicting events when store them. This approach allow a fine grained control over the events. I don't know if this will over complicated the solution or it's a "standard" that I think is pointed out at http://danielwhittaker.me/2014/09/29/handling-concurrency-issues-cqrs-event-sourced-system/
Any gaps in the problem description is appreciated. Thanks in advance!