Mutex lock/unlock step (to prevent race conditions)

Mutex lock/unlock step (to prevent race conditions)

Let’s start with an example:
Database Query user_balance: $10 (query takes e.g. 10ms)
If balance >= 10: Database Update user_balance: user_balance - $10
Database Query user_balance: $0

What happens if the same user performs the very same server action precisely at the same time? (e.g.: 1ms apart)

Database Query user_balance: $10
Database Query user_balance: $10
If balance >= 10: Database Update user_balance: user_balance - $10
If balance >= 10: Database Update user_balance: user_balance - $10
Database Query user_balance: $-10

A mutex lock step would allow a regular Wappler to prevent race conditions (such as the above). You would place a Lock step in the beginning of any time-critical portions of your app, followed by an Unlock at the end.

The mutex lock step would have associated an unlock step. For validation, Wappler UI should count if the number of Lock steps is equal to the number of the Unlock steps.

The mutex lock step would use an underlying filesystem LOCK_EX. This would only work on single-server deployments, not on clusters.

The mutex lock/unlock step would accept a user input (such as the user ID) as locking key.

Example of possible real-world use case:

Strangely enough i was thinking about this exact issue only yesterday, certainly record locking in MySQL should be possible as Wappler leverages InnoDB so using SELECT … FOR UPDATE to ,lock, by inference. may be a solution. Not sure about LOCK_EX as this is a PHP only solution I believe

Thanks for the insights!

The PHP solution was just the easiest example. Here’s a more generic one for Linux servers:
https://linux.die.net/man/2/flock
This means it can be applied to NodeJS as well - it’s about creating a file with a specific property to ensure only one reader/writer can have access to it at the same time, so the Wappler steps should only progress if a file handle was successfully acquired (I believe the script will hang till a lock is acquired)

Maybe this will be solved more easily and natural with database transactions.

We have those in the pipeline, so should be available soon.

12 Likes

Database race condition incident:

Hi @George this feature already done? Thanks i new here and control of transactions for me it is very important!!

1 Like

Hi, @George is the version of wappler released that have transaction pipeline feature? We are also facing similar problems.

We hope to add database transactions soon. Probably on Nodejs first.

3 Likes