This is a very simplified version of the problem:
You have an integer saved on a server called "B" and you have an script saved on a server call "A" exposed to the internet. The script pulls the integer from server B, adds one to it, and then updates the remote integer. None of this operations are atomic, the pulling, the adding and the update, all of them have a random latency.
If there is only one user calling the script in sequence there is not going to be any problems, and the int is going to be incremented consistently. But, since script is exposed to internet, it can be called in parallel from several users at the same time, so while an instance of the script will be incrementing the value locally before updating it remotely, another one will pull the actual value from the remote server, incrementing an old version of it.
My solution is to use a queue (or at least try to); So instead of calling the script, the users will call another script that will write on a DB the execution request (a message; "please call script.php"). Since the writing in the DB is not atomic, I'm also writing the microtime of the server so later I can order the execution requests by it. A third script, usually call called a worker, will query the DB for this messages and process the request.
The problem I have is most of the actual web queue solutions just call the worker every time they need it, because the don't care about order, they just want to make a synchronous job, asynchronous so the website can be faster. I cannot call the worker script every time a new request arrive since the problem will persist, two or more workers can be instantiated at the same time messing the calculations. I can put the worker on a cronjob to be lunch each 60 seconds, but it will be slow for my needs. I can also just put a while loop inside the worker that just query the DB indefinitely but that just seems inefficient to me, or maybe this is actually how queue works? just a while cicle looping till the end of times with maybe an sleep on it... What do you think?