9

I have a simple Silex web app with MySQL/Doctrine ORM. Each User has balance (it's a simple app, so just column is fine) and I need to decrease it after some action (checking that it is > 0 of course).

As I understand I can use optimistic locking to avoid conflicts/vulnerabilities. I have read the docs http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/transactions-and-concurrency.html but I can't find any complete example about using it.

Where do I get the "expected version"? Do I need to pass it as input (hidden form field)? Or there are better ways? The docs say something about session but I don't get how I could store it there (update session on each request?).

Also if I pass it as input, then as I understand there is no way to repeat the query automatically after catching OptimisticLockException without notifying user about that? (for example if user opened two tabs and submitted the request in them one by one)

My goal is just to prevent potential issues when user sends several requests at the same time and balance gets decreased only once etc. So it would be good to be able to repeat it automatically on lock error without involving the user. Because if I pass it via form then getting this error because of multiple tabs is very likely. So it seems kind of complicated, maybe there is something else instead of optimistic locking?

5
  • 1
    Kind of a broad question. I don't have a working example for you. The basic idea is that you need to save the current version of the entity before you pass it onto the user for editing. You could do this with a hidden form element but you run the risk of some jolly joker user changing it's value. Storing it in the session removes this risk. And of course you would have to update it on each request. What to do when the version no longer matches is up to you. Discarding the user's changes without informing them seems a bit rude.
    – Cerad
    Feb 1, 2018 at 15:48
  • @Cerad thank you :) In my case I do not have anything to discard, it just a button that starts (queues) some operation. But my goal is just to prevent potential issues when user sends several requests at the same time and balance gets decreased only once etc. So it would be good to be able to repeat it automatically on lock error without involving the user. Because if I pass it via form (and in the session too I guess) then getting this error because of multiple tabs is very likely. So it seems kind of complicated, maybe I should use something else instead of optimistic locking?
    – Alex P.
    Feb 1, 2018 at 17:35
  • 1
    I think CQRS and event sourcing is closer to what you want. kenneth-truyers.net/2013/12/05/… and cqrs.nu Optimistic locking is really all about two or more users trying to update the same record at the same time.
    – Cerad
    Feb 1, 2018 at 18:19
  • Please provide a SHOW CREATE TABLE when Optimistic is in use and when it is not. I am fishing for an extra column (probably a TIMESTAMP) that helps with the "optimistic" algorithm.
    – Rick James
    Feb 1, 2018 at 23:17
  • @RickJames what do you mean? I was going to use version integer column like in the docs above.
    – Alex P.
    Feb 2, 2018 at 6:32

3 Answers 3

7
+50

You should only use locking for operations that can't be executed atomically. So if possible avoid querying the object, checking the amount and then updating it. If instead you do:

update user set balance = (balance + :amount) 
where (balance + :amount) >= 0 
and id = :user_id

This you will check and update in one operation, updated rows count will be 1 if the check passed and the balance was updated and 0 otherwise.

2
  • Yeah, good idea, seems like it's suitable for my case (except that I need to decrease, not increase the balance). :) Just need to figure out how to get that count in Doctrine...
    – Alex P.
    Feb 7, 2018 at 21:46
  • Amount can be negative, that's why I put the check there.
    – dhinchliff
    Feb 8, 2018 at 10:01
5

Create a column named "version" in the "user" table and make it a "timestamp" column ( with "on update CURRENT_TIMESTAMP" attribute). So, "User" ORM class will look like below :

class User
{
    // ...
    /** @Version @Column(type="timestamp") */
    private $version;
    // ...
}

Now, read the current record with its "version".

$theEntityId = YOUR ENTITY ID;
$entity = $em->find('User', $theEntityId);
$expectedVersion = entity->version;
try {
   // assert version
    $em->lock($entity, LockMode::OPTIMISTIC, $expectedVersion);

    // do the work

    $em->flush();
} 
catch(OptimisticLockException $e) {
    echo "Sorry, but someone else has already changed this entity. Please apply the changes again!";
}
4
  • Are you sure that it's safe? Seems like it's similar to the case described in the docs to explain why we need to pass it via form or store in session.
    – Alex P.
    Feb 3, 2018 at 19:18
  • Ya. It's safe. Because, at any point of time, only one user can have the same version number between data selection and updation. I am not recommending to pass it through form or session. I am suggesting to create a 'version' column in the table and it will ensure that the update operation happens sequentially or fails gracefully if the version number gets updated because of another user.
    – sudip
    Feb 3, 2018 at 19:31
  • @sudip Nope. This is not optimistic locking. Optimistic locking applies when you send the entity out to be edited and want to guard against the possibility that someone else might come along and update the entity while the first user is taking a lunch break. docs.doctrine-project.org/projects/doctrine-orm/en/latest/… No explicit locking involved. What's puzzling about this question is that there is some kind of "queue" thing going on. An answer is not possible without more details.
    – Cerad
    Feb 3, 2018 at 22:50
  • @Cerad it's not related to queue, I simply need to decrease user's balance by some amount (or return error) when user clicks a button (sends request to server) and also set some status for specified entity (later server will detect that status and perform some task). What server does after that is not really important. Basically the "balance" just limits the user so they wouldn't repeat that action too often.
    – Alex P.
    Feb 3, 2018 at 23:17
0

Optimistic lock will allow concurrent access to read the entity (meaning that there might be some threads that will read out of date data) , while Pessimistic lock will lock reading if someone is performing an operation on that registry.

Depends on how critically accurate you want your concurrent access to be?! Is it ok to read out of date Data?

Eg:

{OTIMISTIC LOCK}
Thread1 -> read(balance1[200$][version=1])
Thread2 -> read(balance1[200$][version=1])
Thread1 -> balance.add(100$).save()[300$ total and version=2]
Thread2 -> balance.add(50$).save()[OtimisticLockError Version-> 2 != 1]

{PESSIMISTIC LOCK}
Thread1 -> read(balance1[200$]) [lock for update | select for update |... depends on DB])
Thread2 -> read(balance1) [Pessimistic lock exception]
Thread1 -> balance.add(100$).save()[300$ total]
Thread1 -> release lock balance1
Thread2 -> read(balance1[300$]) Ok

OPTIMISTIC LOCK

PESSIMISTIC LOCK

PESSIMISTIC vs. OPTIMISTIC

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.