search
HomeBackend DevelopmentPHP TutorialPHP optimistic locking combined with transaction deduction balance failed: How to ensure that the balance is correctly deducted in concurrency situations?

PHP optimistic locking combined with transaction deduction balance failed: How to ensure that the balance is correctly deducted in concurrency situations?

PHP Optimistic Locking Combined with Database Transactions to Deduct Balance: Problem Analysis and Solution

This article discusses how to avoid concurrency problems that lead to failure of balance deduction or inconsistent data when using optimistic locks and database transactions for balance deduction in PHP environment. We will analyze the error code and provide the correct solution.

Problem code analysis and error reasons:

The following code snippet attempts to ensure the correctness of balance deductions in concurrent environments through optimistic locks and transactions, but has flaws:

Error code snippet 1:

 public function userbuy()
{
    $user = $this->getuser(); 
    $oldmoney = $user['balance']; 
    $orderoffer = $this->getordermoney($orderid); 
    if($oldmoney error('Insufficient Account Balance');

    //Optimistic locking solution (wrong points)
    $newmoney = $oldmoney - $orderoffer['price']; 
    $newuser = smsuser::where(['id' => $user['id'],'balance' => $oldmoney])->find();
    if(!$newuser) $this->error('user does not exist');
    //Open database transaction db::transaction(function () use($newuser,$orderid,$newmoney){
        $newuser->balance = $newmoney;
        $result = $newuser->save();
        if(!$result) $this->error('Save balance failed');

         //Create an order code
         //Deduct inventory code
         //Create user balance change record code    
        db::commit(); //Commit transaction (excessive operation)        
    });
}

Cause of error:

  1. Optimistic lock position error: find() method is executed outside the transaction. Multiple concurrent requests get the same $oldmoney value. Only save() operation of the first request succeeds, and subsequent requests fail because balance is no longer equal to $oldmoney . The conditional judgment of optimistic locking should be made in update statement.

  2. db::commit() redundant: db::transaction() method itself will automatically commit the transaction unless an exception rollback occurs. Manual call to db::commit() is redundant and may mask errors.

Error code snippet 2:

 public function userbuy()
{
    // ... (The code is the same as above, the part is omitted) ...

    //Optimistic locking solution (wrong points)
    $newUser->balance = $newMoney;
    $result = $newUser->save();
    if(!$result) $this->error('Save balance failed');

    //Open database transaction (Error)
    Db::transaction(function() use(){
         //Create an order code
         //Deduct inventory code
         //Create user balance change record code    
        Db::commit(); //Commit transaction (excessive operation)         
    });
}

Cause of error:

The balance update operation is executed outside the transaction. If subsequent operations (creating orders, deducting inventory, etc.) fail, the balance has been updated, resulting in inconsistent data.

Correct solution:

The conditional judgment of optimistic locking should be placed in the database update statement, and all operations that need to ensure atomicity should be included in the same transaction.

Correct code:

 public function userbuy()
{
    $user = $this->getuser();
    $oldmoney = $user['balance'];
    $orderoffer = $this->getordermoney($orderid);
    if ($oldmoney error('Insufficient Account Balance');

    $newmoney = $oldmoney - $orderoffer['price'];

    // Use optimistic locking mechanisms for databases (such as MySQL)
    $affectedRows = smsuser::where('id', $user['id'])
        ->where('balance', $oldmoney)
        ->update(['balance' => $newmoney]);

    if ($affectedRows === 0) {
        $this->error('Balance update failed, there may be concurrent conflict'); // Optimistic lock failed return;
    }

    // Enable the transaction, including all subsequent operations db::transaction(function () use ($orderid, $newmoney, $user) {
        // Create an order code
        // Deduct inventory code
        // Create user balance change record code (make sure these operations are also included in the transaction)
    });
}

This solution places balance updates and subsequent operations in the same transaction and uses the optimistic locking mechanism provided by the database to ensure data consistency. If any operation fails, the transaction will automatically roll back to ensure data security. Avoid manually committing transactions, simplifying code and improving readability. If the number of rows affected by the update statement is 0, it means that the optimistic lock fails and concurrent conflicts need to be handled. Such situations can be handled using retry mechanisms or other strategies. The specific optimism lock implementation depends on the database system used.

The above is the detailed content of PHP optimistic locking combined with transaction deduction balance failed: How to ensure that the balance is correctly deducted in concurrency situations?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)