How to handle the result of an operation that may depends on inconsistent data

53 Views Asked by At

Let's imagine i'm creating an use case. It's in oriented object (OO) language, part of my business rules are in service layer, and part are on classes/objects. I've a specific use case, that in pseudo code is something like this:

1. myUseCase(...) {
2.  someData = dbConn.fetchSomeData(); // from database
3.  result = new ClassWithBusinessRule(someData).veryCostlyOperation(someData);
4.  dataWillBeSavedInDatabase = MapResult.aMapFunction(result);
5.  dbConn.transactionStart();
6.  dbConn.save(dataWillBeSavedInDatabase);
7.  dbConn.maybeOtherOperations(...);
8.  dbConn.transactionCommit();
9. }

PS: It's just an example easy to read, this language doesn't exist.

It's well known that we should mantain a transaction with few operations and fast, so veryCostlyOperation should not be in the transaction. In some scenario, of concurrent operations, maybe two users could execute operations (not necessarily the same) in almost same time. Let's conceive that these two users are changing same set of data (SomeData). The sequence of operations are:

  1. First user fetch some data (line 2)
  2. First user execute lines 3 and 4
  3. Second user change the same set of "SomeData" that first user used to execute lines 3 and 4 (data is inconsistent)
  4. First user will execute the rest of code

In this sequence of operations, "dataWillBeSavedInDatabase" was calculated from old incorrect data.

What are the possibilities to handle with this situation?

0

There are 0 best solutions below