Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Sourcing and optimistic concurrency control

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!

like image 634
martinezdelariva Avatar asked Mar 24 '16 12:03

martinezdelariva


1 Answers

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.

like image 164
guillaume31 Avatar answered Oct 21 '22 17:10

guillaume31