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!
Upon trying to append an event to a stream, you can specify an expected current version number and throw if the actual current number doesn't match it.
This kind of optimistic concurrency mechanism is built into some event storage systems.
The article you linked to seems to describe a similar approach but more powerful since you have access to the type of events that occurred since the expected version and can detect conflicts based on more fine-grained criteria.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With