Optimistic concurrency is a strategy for dealing with conflicting writes to a database. The example often used is when two users update the same piece of information at the same time. If no strategy is in place to deal with this situation, information can go lost. This is referred to as “Last write wins”. A pessimistic strategy would be to first obtain a lock on the piece of information to be updated. This ensures no one else can save until we have released the lock. Finally, an optimistic strategy involves validating that the piece of information hasn’t been modified by a different user and hoping for the best. If it has been modified, the operation is canceled and we have to somehow resolve the conflict.
One simple way to detect conflicts is to compare the initial state of an entity with it’s current state in the database. Using OrigoDB, this could look something like this:
This is a CRUD based solution. If any field has been modified, we abort. If you want to be more domain specific or granular you could do:
The Model base class has a Revision property which is incremented by the engine for each command executed. To be very strict you could require a specific revision during writes, ensuring no part of the database was modified since the view was rendered. A different approach would be tagging every entity modified during a write with the resulting Revision instead of a version per entity. Here’s a partial generic entity model showing how this could be achieved:
What is a conflicting write?
The examples above were based on users modifying the same entities. which is not the only type of conflict which can arise. In the following domain specific example a bid is only placed if the highest bid hasn’t changed.
Having a strategy for dealing with write conflicts in a concurrent system is an absolute necessity. In addition, you need to consider the possible anomalies on a per transaction basis. The generic entity example above will not prevent conflicts of the kind in the PlaceBid example.